开发者

How to cut the string?

开发者 https://www.devze.com 2023-03-09 17:30 出处:网络
if I have a string e.g. var myStr="AAAAAAA BBBBB CCCCC DDDDD...", this string can have various length contain words with spaces开发者_开发问答.

if I have a string e.g. var myStr="AAAAAAA BBBBB CCCCC DDDDD...", this string can have various length contain words with spaces开发者_开发问答.

I would like to have a function which will sperate the string into an array, that's the string will be cut to segements as elements in the array, where each element of the array contain the words from the string with total length(including space between words) less tha 10 characters long.

(Each element of array always contain complete words & space between words, not cut word from the middle)

I tried:

var words=myStr.split(' ');

then.... what is the efficient way to implement?


try:

var words = myStr.replace(/(\s)/g, ' ').split(' ');

(from head, not tested)


var words = "AAAAAAA BBBBB  CCCCC   DDDDD\tEEEE \t FFFF".split(/\s+/);

Once you have the words, you can iterate over words and push each word into a new array as follows:

EDIT #2

var words = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vulputate, velit et luctus tristique, libero quam ornare ligula, sagittis consequat massa tellus vel nulla.".split(
  /\s+/
);
var output = [words[0]];
for (var i = 1; i < words.length; i++) {
  var word = words[i];
  var prev = output.pop();
  if ((prev + " " + word).length <= 10) {
    output.push(prev + " " + word);
  } else {
    output.push(prev);
    output.push(word);
  }
}
console.log(output);
// ["Lorem", "ipsum", "dolor sit", "amet,", "consectetur", "adipiscing", "elit. Sed", "vulputate,", "velit et", "luctus", "tristique,", "libero", "quam", "ornare", "ligula,", "sagittis", "consequat", "massa", "tellus vel", "nulla."]


For example:

var myStr = 'xxx yy wwwwww vvvv bbbbbbbbb cccccccccc a ddddddddddd eee';
var myArray = myStr.match(/.{1,10}(\s|$)|\S{1,10}(?!\s)/g);
for (var i in myArray) myArray[i] = myArray[i].replace(/\s+$/, '');
// myArray => [ 'xxx yy', 'wwwwww', 'vvvv', 'bbbbbbbbb', 'cccccccccc', 'a', 'dddddddddd', 'd eee' ]

Edit 2011-05-31: reflects clarified requirements

0

精彩评论

暂无评论...
验证码 换一张
取 消