Frank Fiegel
Frank Fiegel

Reputation: 193

How to split text at white-space while keeping the space?

'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

Answers (1)

C3roe
C3roe

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

Related Questions