Reputation: 193
'foo bar'.split(' ')
> ['foo', 'bar']
'foo bar'.split(' ')
> ['foo', '', '', 'bar']
'foo bar'.split(/\+s/)
> ['foo', 'bar']
Where as what I want is:
'foo bar'.?
> ['foo', ' ', 'bar']
i.e. I want to split the text at a white space, but I want to capture the whitespace (however long) in the resulting array.
Upvotes: 0
Views: 171
Reputation: 96250
Use a regular expression, and capture what you are splitting at, by putting it into round brackets:
'foo bar'.split(/( )/)
> ['foo', ' ', 'bar']
To capture any amount of any whitespace characters, use the \s
class and the +
quantifier:
'foo bar'.split(/(\s+)/)
Upvotes: 4