3

I have an string array like this:

var strings = ['elephant-rides', 'are', 'fun!'];

How can I achieve the result like given below?

var result = ['elephant', '-', 'rides', 'are', 'fun', '!'];
shinjw
  • 3,105
  • 3
  • 18
  • 40
  • https://stackoverflow.com/questions/25266372/javascript-splitting-a-string-at-special-character – afikri Jul 06 '20 at 07:46

1 Answers1

10

You could match word or not word characters in a flat array.

var strings = ['elephant-rides', 'are', 'fun!'],
    result = strings.flatMap(s => s.match(/\w+|\W+/g));

console.log(result);
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358