2

I am trying to use javascript replace() with a regex expression so that when it matches certain characters like: .,!? it will replace the matched character with itself surrounded by spaces. For example the string "hello?!?" will become "hello ? ! ? ".

Is there a better way than just doing a string.replace() for each character I wish replace?

I know I can select on the characters easy enough with '/[!\?\.]/g', but getting it to replace it with the same character it matched with is eluding me.

3
  • Should there be one or two spaces between ? and ! in your example? Commented Jul 10, 2013 at 19:32
  • Either way, after I split the sentence using / +/g which accounts for any number of spaces being between them to account for user error Commented Jul 10, 2013 at 19:35
  • If the number of spaces does not matter then the answer of LeonardChallis is the one you are looking for. Commented Jul 10, 2013 at 19:37

2 Answers 2

5

It's as simple as adding a back-reference, like so:

"hello?!?".replace(/([!?\,\.])/g, ' $1 ');
Sign up to request clarification or add additional context in comments.

5 Comments

Is there any sort of escape for the back reference? Doing the above gives me "hello $1 $1 $1".
This will add two spaces between consecutive special characters.
@Scott101 I edited to escape the period in the regex, as well as add the comma in your request above. If you copy/paste the line above and run it in the js console in your browser, it works as requested.
@go-oleg That is ok for what I am doing as I immediately split the string using / +/g. The string is user input that I need to break up and I don't trust them to not put in multiple spaces between words.
@Tracker1 Awesome thanks, forgot to surround the regex in the parentheses. I'll have to wait to accept the answer in 3 min as stack overflow won't let me accept it yet.
0

If '/[!\?.]/g' matches as a regex, just capture the group by surrounding it with ()'s '/([!\?.])/g'

Then use the returned matched group to get the character you matched

Comments

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.