最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin3PV0评论

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 bee "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.

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 bee "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.

Share Improve this question edited Jul 10, 2013 at 19:33 t.niese 40.9k9 gold badges78 silver badges109 bronze badges asked Jul 10, 2013 at 19:26 Scott101Scott101 1382 silver badges9 bronze badges 3
  • Should there be one or two spaces between ? and ! in your example? – t.niese 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 – Scott101 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. – t.niese Commented Jul 10, 2013 at 19:37
Add a ment  | 

2 Answers 2

Reset to default 5

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

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

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

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far