How to split array elements by special characters

Viewed 187

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', '!'];
1 Answers

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);

Related