1

I have a string like "Azarenke V. Su Simple 90" and I need to split it and put all words in array. I using this code:

var s = "Azarenke   V.   Su   Simple 90";

var array = s.split(/(\ +)/);
console.log(JSON.stringify(array));

but the result is:

"["Azarenke","   ","V.","   ","Su","   ","Simple"," ","90"]"

Where is some 'empty' strings contains only spaces. But I do not whant to push them in output array. I familiar in C# and .net, it has something like RemoveEmptyEntries but can't find the same in javascript. How to solve this task? Possible I need to make some remarks in regular expression?

Alexey Kulikov
  • 1,097
  • 1
  • 14
  • 38

3 Answers3

2

Try without (capturing) parens

var s = "Azarenke   V.   Su   Simple 90";

var array = s.split(/\s+/);
console.log(JSON.stringify(array)); 
// Output:  ["Azarenke","V.","Su","Simple","90"]
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
1

Just remove the capturing group. Capturing group will keep up the delimiters. That is , it splits the input according to the delimiter and also it prints out the delimiter at the final.

> var s = "Azarenke   V.   Su   Simple 90";
undefined
> s.split(/\s+/);
[ 'Azarenke',
  'V.',
  'Su',
  'Simple',
  '90' ]
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

You can replace multiple spaces with single spaces first, using:

`Azarenke   V.   Su   Simple 90`.replace(/ +(?= )/g,'');

Then you can split by a space.

halafi
  • 1,064
  • 2
  • 16
  • 26