Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split array elements by special characters [closed]

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', '!'];
like image 273
Tirlochan Arora Avatar asked Apr 25 '26 14:04

Tirlochan Arora


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);
like image 114
Nina Scholz Avatar answered Apr 27 '26 03:04

Nina Scholz