Quick javascript answer

Just a quick question about the split function

How can I split my line in every second space?

myArray = 'This is a sample sentence that I am using'
myArray = myString.split(" ");

I would like to create an 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 space, how would I deal with it ...?

any help would be appreciated

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

Not a beautiful solution. It is assumed that the character is \1not 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);
+1
source

, :

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 ,

+1

Source: https://habr.com/ru/post/1732644/


All Articles