2

For example, the following string: " Hello Wor$LD !! " should be converted to :

["  ","Hello","  ","Wor$LD"," ","!!"," "]

I tried to split the string using \b , but it fails when there are non-word characters, such as $ and !.

Note that all white spaced should be grouped together.

Yair
  • 508
  • 1
  • 4
  • 12

1 Answers1

4

You can match the groups which either only contain whitespaces or don't contain any.

"  Hello  Wor$LD !! ".match(/\s+|\S+/g);

Note that if the string is empty, it will return null. If you want an empty array, add || [] at the end.

Oriol
  • 274,082
  • 63
  • 437
  • 513