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>+" ");
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 "))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With