Gerald Ferreira
Gerald Ferreira

Reputation: 1337

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

Upvotes: 3

Views: 395

Answers (3)

John Kugelman
John Kugelman

Reputation: 361585

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

Upvotes: 2

Marius
Marius

Reputation: 58921

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

Upvotes: 1

kennytm
kennytm

Reputation: 523224

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

Upvotes: 1

Related Questions