Frogtown
Frogtown

Reputation: 49

Array from string including special characters

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

Answers (1)

CertainPerformance
CertainPerformance

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

Related Questions