Scott101
Scott101

Reputation: 138

Javascript, regex: Replace specified characters with space and matched character

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.

Upvotes: 2

Views: 6441

Answers (2)

LeonardChallis
LeonardChallis

Reputation: 7783

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

"hello?!?".replace(/([!?\,\.])/g, ' $1 ');

Upvotes: 5

Evan Knowles
Evan Knowles

Reputation: 7501

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

Upvotes: 0

Related Questions