2

I would like to split a string like that:

"'Hi, how are you?' he said."

in this array:

["'", "Hi", ",", " ", "how", " ", "are", " ", "you", "?", "'", " ", "he", " ", "said", "."]

in my js script. I tried with some regexp, but I'm not very good at using it. Can anyone help me?

0

2 Answers 2

3

This is what I'd probably use:

"'Hi, how are you?' he said.".match(/\w+|./g);

It performs a global match for words (\w+) and other characters (.) in the given string.

Sign up to request clarification or add additional context in comments.

3 Comments

Exactly what I needed. Thank you, I'll accept your answer asap.
Anyway, I've noticed that with this regex I've lost all the \n characters in my string, any suggestion to keep them?
@Federinik Just add the \n to the other characters group. Can also be done with /\w+|\W/g.
2
"'Hi, how are you?' he said.".match(/\w+|\W/g)

//output
["'", "Hi", ",", " ", "how", " ", "are", " ", "you", "?", "'", " ", "he", " ", "said", "."]

Explanation

\w+ - For Matching Group of Characters

\W - For Matching Non-Character

| - Or operator between above two (either a Character or a non character)

1 Comment

The i modifier is actuall not necessary since you only use case-independent character classes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.