I’m trying to write a function to split a word into letters, and I’m getting a weird result:
'abc'.split(/(a|b|c)/)
Gives:
["", "a", "", "b", "", "c", ""]
Incidentally, I see the same results in Python, so clearly the problem is me!
>>> re.split( '(a|b|c)', 'abc')
['', 'a', '', 'b', '', 'c', '']
The problem is, why are there empty strings intercalated between the letters? I expected
["a", "b", "c"]
Thanks!
I’m trying to write a function to split a word into letters, and I’m getting a weird result:
'abc'.split(/(a|b|c)/)
Gives:
["", "a", "", "b", "", "c", ""]
Incidentally, I see the same results in Python, so clearly the problem is me!
>>> re.split( '(a|b|c)', 'abc')
['', 'a', '', 'b', '', 'c', '']
The problem is, why are there empty strings intercalated between the letters? I expected
["a", "b", "c"]
Thanks!
Instead of splitting, you can do a string match with a global regex...
'abc'.match(/(a|b|c)/g); // ["a", "b", "c"]
This makes more sense since all you really care about is the match, not what's between the match.
If you wanted to match any character from a to z, you can do this...
'abc'.match(/([a-z])/gi);
I made it case insensitive to match upper case too.
There are empty strings between your delimiters because you're splitting on those letters. a
, b
, and c
are the "delimiter" tokens, and ''
is the actual "word" you've got in between.
For example, if you were to split "x,y"
on ','
, you'd expect to get back "x", ",", and "y". If you split ",y"
on ','
, you get back "", ",", and "y". So if you split "ay"
on 'a'
, your output is "", "a", and "y".
See this page:
If separator is a regular expression that contains capturing parentheses, then each time separator is matched the results (including any undefined results) of the capturing parentheses are spliced into the output array. However, not all browsers support this capability.
If you remove the parentheses, you'll get the expected result:
> 'abc'.split(/a|b|c/)
["", "", "", ""]
That is, you'll split your string wherever there's an "a", "b", or "c", leaving only the spaces in between.
But it sounds like that's not what you want. If you want the result ["a", "b", "c"], use "match", as someone suggested below.
Other answers have covered the regular expression angle, but
I’m trying to write a function to split a word into letters
For your stated goal you don't need a regular expression at all. Just pass an empty string to .split()
:
'abc'.split('')
The result will be:
['a','b','c']