I'm trying to split a string into an array of words, however I want to keep the spaces after each word. Here's what I'm trying:
var re = /[a-z]+[$\s+]/gi;
var test = "test one two three four ";
var results = test.match(re);
The results I expect are:
[0]: "test "
[1]: "one "
[2]: "two "
[3]: "three "
[4]: "four "
However, it only matches up to one space after each word:
[0]: "test "
[1]: "one "
[2]: "two "
[3]: "three "
[4]: "four "
What am I doing wrong?
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace.
Split(String) Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor.
Consider:
var results = test.match(/\S+\s*/g);
That would guarantee you don't miss any characters (besides a few spaces at the beginnings, but \S*\s*
can take care of that)
Your original regex reads:
[a-z]+
- match any number of letters (at least one)[$\s+]
- much a single character - $
, +
or whitespace. With no quantifier after this group, you only match a single space.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With