Reputation: 49
How can I make an array from a string and include special characters as standalone values?
var str = "Hi, how are you doing?";
var TxtArray = str.split(" ");
The output will be:
Hi,,how,are,you,doing?
Now I want the output to be:
Hi,,,how,are,you,doing,?
Notice the (,) and (?) are separated in the array
Upvotes: 1
Views: 316
Reputation: 371019
If you use match
instead of split
, you can then use a regular expression that matches word characters (\w
), OR matches your special characters ([,?]
) to get your desired result:
var str = "Hi, how are you doing?";
console.log(str.match(/\w+|[,?]/g))
Upvotes: 3