简体   繁体   English

将JavaScript(nodeJS)字符串拆分为固定大小的块

[英]Split JavaScript(nodeJS) string into fixed sized chunks

I want to split a string into fixed sized chunks (say 140 characters each) in JavaScript using space as delimiter(ie it should not break words), Note: It should handle newline character Currently I'm using wordwrap npm package, but It does not handle new-line character. 我想使用空格作为定界符在JavaScript中将字符串拆分成固定大小的块(每个块140个字符)(即,它不应打断单词), 注意:它应该处理换行符当前我正在使用wordwrap 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));

It works fine for normal text but if text contains new-line carriage I get following error: 它适用于普通文本,但是如果文本包含换行符,则会出现以下错误:
SyntaxError: Unexpected token ILLEGAL 语法错误:意外的令牌非法
at exports.runInThisContext (vm.js:73:16) 在exports.runInThisContext(vm.js:73:16)
at Module._compile (module.js:443:25) 在Module._compile(module.js:443:25)
at Object.Module._extensions..js (module.js:478:10) 在Object.Module._extensions..js(module.js:478:10)
at Module.load (module.js:355:32) 在Module.load(module.js:355:32)
at Function.Module._load (module.js:310:12) 在Function.Module._load(module.js:310:12)
at Function.Module.runMain (module.js:501:10) 在Function.Module.runMain(module.js:501:10)
at startup (node.js:129:16) 在启动时(node.js:129:16)
at node.js:814:3 在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); 

If you want to remove the trailing space, you can use trim() : 如果要删除尾随空格,可以使用trim()

slices.push(str.slice(0, lastSpace).trim());

I was originaly trying to implement Randy's answer, but found I need different implementation: 我本来试图实现Randy的答案,但是发现我需要不同的实现:

  • batch size as parameter, 批量大小作为参数,
  • didn't like the while loop 不喜欢while循环
  • and thought it could be done without spliting the string. 并认为无需拆分字符串就可以完成。

Here's my solution: 这是我的解决方案:

 var testString = "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 stringChunks(str, chunkSize) { chunkSize = (typeof chunkSize === "undefined") ? 140 : chunkSize; let resultString = ""; if ( str.length>0 ) { let resultArray = []; let chunk = ""; for ( let i = 0; i<str.length; i=(i+chunkSize) ) { chunk = str.substring(i,i+chunkSize); if ( chunk.trim()!="" ) { resultArray.push(chunk); } } if (resultArray.length) { resultString = resultArray.join("/\\n"); } } else { resultString = str; } return resultString; } console.log( stringChunks(testString) ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM