在特殊字符后添加文本

Add text after a special character

我有一个带标点符号的字符串,我想在所有符号后添加  

例如,这个字符串:

Hi there, how are you ? Ok/not_ok !

我希望它变成这样:

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

我在考虑 replace 函数,但我需要为所有符号调用它很多次...

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

是否有更简单的方法仅使用 1 个函数来实现此目的?我在考虑正则表达式,类似于此:

str.replace([/,!?_],<selection>+"&thinsp;");

使用基于捕获组的正则表达式。这会将特殊字符捕获到一个组中。稍后我们可以通过在替换部分中指定组索引号和 $ 符号来引用那些捕获的字符(like </code>、<code>) .

var s = "Hi there, how are you ? Ok/not_ok !"
alert(s.replace(/([\/,!?_])/g, "&thinsp;"))