0

I want to split a line of text by whitespaces (i.e. get rid of all whitespaces and leave the rest as separate elements). I have this code:

line.split(/\s+/);

but it doesn't work exactly how I want. For example hi there! it splits to: [hi,there!,] (notice 1 empty element at the end of the array). How to split a line without that last empty element?

NPS
  • 6,003
  • 11
  • 53
  • 90

5 Answers5

4

Are you sure there isn't an empty space at the end of your string? Cuz it's working for me.

In any case, try this:

line.replace(/^\s+|\s+$/g,'').split(/\s+/);

This will remove any whitespace from the start and end of the string before splitting.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • As i suspected the problem was in windows style EOL encoding. I didn't have spaces at the end of lane but `\r` formed the last 'empty' element. Anyway, your solution is universal (works both with windows and unix style encodings) so that's what I was looking for. Thx! – NPS Nov 28 '12 at 01:37
  • Just wondering - is there a reason why you use the `g` mod when using `^ $`? I'm probably misunderstanding the uses – Ian Nov 28 '12 at 01:44
  • If the string has spaces at the start and the end, these are two separate matches of the regex and both need replacing. Hence the need for `g`. – Niet the Dark Absol Nov 28 '12 at 01:58
  • Ahh! Yes, I don't know why I didn't think of that logic. That makes sense, thanks. – Ian Nov 28 '12 at 02:09
2

call .trim() before splitting the String, it will remove whitespaces before and after your String

Valentino Ru
  • 4,964
  • 12
  • 43
  • 78
2
line.trim().split(/\s+/);

This should do what you want.

Andrew Hubbs
  • 9,338
  • 9
  • 48
  • 71
0

Wouldn't it be easier to do

line.match(/\S+/g); // => ["hi", "there!"]
Bruno
  • 5,772
  • 1
  • 26
  • 43
-1

Why not simply use

line.split(' ');

it splits "Hi there!" into

["hi", "there!"]
bPratik
  • 6,894
  • 4
  • 36
  • 67