3

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

3 Answers 3

2
myString = 'This is a sample sentence that I am using';
myArray = myString.match(/[^ ]+( +[^ ]+){0,2}/g);
alert(myArray);
Sign up to request clarification or add additional context in comments.

1 Comment

Ah this is much better. (And I think (?:...) should be used instead of (...) in this case.)
1

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);

Comments

1

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

1 Comment

You can replace the loop body with a simple: ret.push(arr.slice(i, i+count).join(splt));.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.