Splitting a string into an array of words using regular expressions

I am trying to split a string into an array of words, however I want to keep spaces after each word. Here is what I am trying:

var re = /[a-z]+[$\s+]/gi;
var test = "test   one two     three   four ";
var results = test.match(re);

Expected results:

[0]: "test   "
[1]: "one "
[2]: "two     "
[3]: "three   "
[4]: "four "

However, it matches only one space after each word:

[0]: "test "
[1]: "one "
[2]: "two "
[3]: "three "
[4]: "four "

What am I doing wrong?

+5
source share
5 answers

Consider:

var results = test.match(/\S+\s*/g);

This ensures that you don't miss a single character (except for a few spaces at the beginning, but \S*\s*can take care of that)

Your original regex:

  • [a-z]+ - matches any number of letters (at least one)
  • [$\s+] - - $, + . .
+7

:

test.match(/\w+\s+/g); // \w = words, \s = white spaces
+2

+ char. * char.

/[a-z]+\s*/gi;

+ char +, char. * , .

+1

+ . : [\s]+ \s+ ($ ).

0

RegEx, , , .

Try:

var re = /[a-z]+($|\s+)/gi

or, for a non-capture group (I don't know if you need this with a flag /g):

var re = /[a-z]+(?:$|\s+)/gi
0
source

All Articles