开发者

Quick javascript split question

Just a quick question regarding the split function

How can I split my string at every 2nd space?

myArray = 'This is a开发者_开发问答 sample sentence that I am using'
myArray = myString.split(" ");

I would like to create a array like this

This is a < 2 spaces
sample sentence that < 2 spaces
that I am  < 2 spaces

and if the last word is not a space how would I handle this...?

any help would be appreciated


myString = 'This is a sample sentence that I am using';
myArray = myString.match(/[^ ]+( +[^ ]+){0,2}/g);
alert(myArray);


Not a beautiful solution. Assumes the \1 character isn't used.

array = 'This is a sample sentence that I am using';
array = array.replace(/(\S+\s+\S+\s+\S+)\s+/g, "$1\1").split("\1");
// If you want multiple whitespaces not merging together
//   array = array.replace(/(\S*\s\S*\s\S*)\s/g, "$1\1").split("\1");
// If you only want to match the space character (0x20)
//   array = array.replace(/([^ ]+ +[^ ]+ +[^ ]+) +/g, "$1\1").split("\1");
alert(array);


Split it every space, and then concatenate every other element:

function splitOnEvery(str, splt, count){
  var arr = str.split(splt);
  var ret = [];
  for(var i=0; i<arr.length; i+=count){
    var tmp = "";
    for(var j=i; j<i+count; j++){
      tmp += arr[j];
    }
    ret.push(tmp);
  }
  return ret;
}

Havent tested the code, but should work

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜