Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add text after a special character

I have a string which is punctuated and I would like to add   after all symbols.

For example, this string:

Hi there, how are you ? Ok/not_ok !

I expect it to become like this:

Hi there,  how are you ?  Ok/ not_ ok ! 

I was thinking about the replace function, but I'll need to call it lot of times for all symbols...

str.replace("/","/ ");
str.replace(",",", ");
str.replace("!","! ");
str.replace("?","? ");
str.replace("_","_ ");

Is there an easier way to achieve this using only 1 function? I was thinking about regexp, something similar to this:

str.replace([/,!?_],<selection>+"&thinsp;");
like image 992
Luckyn Avatar asked Dec 02 '25 01:12

Luckyn


1 Answers

Use capturing group based regex. This would capture the special characters into a group. Later we could refer those captured characters by specifying the group index number along with the $ symbol in the replacement part (like $1, $2).

var s = "Hi there, how are you ? Ok/not_ok !"
alert(s.replace(/([\/,!?_])/g, "$1&thinsp;"))
like image 191
Avinash Raj Avatar answered Dec 04 '25 14:12

Avinash Raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!