NPS
NPS

Reputation: 6355

Splitting text in JS by whitespaces

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?

Upvotes: 0

Views: 241

Answers (5)

Bruno
Bruno

Reputation: 5822

Wouldn't it be easier to do

line.match(/\S+/g); // => ["hi", "there!"]

Upvotes: 0

Andrew Hubbs
Andrew Hubbs

Reputation: 9426

line.trim().split(/\s+/);

This should do what you want.

Upvotes: 2

Valentino Ru
Valentino Ru

Reputation: 5052

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

Upvotes: 2

bPratik
bPratik

Reputation: 7019

Why not simply use

line.split(' ');

it splits "Hi there!" into

["hi", "there!"]

Upvotes: -1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

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.

Upvotes: 4

Related Questions