最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

斯普利特的JavaScript(的NodeJS)字符串转换成固定大小的块

运维笔记admin8浏览0评论

斯普利特的JavaScript(的NodeJS)字符串转换成固定大小的块

斯普利特的JavaScript(的NodeJS)字符串转换成固定大小的块

我想将一个字符串分解成固定大小的块使用空间作为分隔符(即它不应该打破的话),注意在JavaScript(说每140个字符):应该处理换行符目前我使用换行NPM包,但它确实无法处理换行符。

var wrap = require('wordwrap')(140)    
var str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum"
console.log(wrap(str));

它工作正常的普通的文本,但如果文本包含新线车厢我收到以下错误: 语法错误:意外标记非法 在exports.runInThisContext(vm.js:73:16) 在Module._compile(module.js:443:25) 在Object.Module._extensions..js(module.js:478:10) 在Module.load(module.js:355:32) 在Function.Module._load(module.js:310:12) 在Function.Module.runMain(module.js:501:10) 在启动时(node.js中:129:16) 在node.js中:814:3

回答如下:

// define string variable
var string = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum"

function sliceMyString(str){
// initialize array (not required but verbose)
    var slices = [];

// while string is not empty
// take 140 characters
// check witch one was the last space or if the end of the line is reached
// then => push them in slices
// then => remove them from the string

    while(str != ''){
        var lastSpace = 0;

        for(var i = 0; i < str.length && i < 140; i ++){
            if(str[i] == ' '){
                lastSpace = i;
            }
            if(i == str.length - 1){
                lastSpace = str.length;
            }
        }

// insert into array (including trailing space, see below the codeblock)
        slices.push(str.slice(0, lastSpace));
        str = str.slice(lastSpace);
    }

// just logging the variables in the slices array

    slices.map(function(slice){
        console.log(slice);
    });
}

sliceMyString(string);
发布评论

评论列表(0)

  1. 暂无评论