正则表达式:搜索特殊字符并删除所有空格 + 易碎字符

时间:2021-05-01 08:36:52

标签: javascript regex

我想在 [:?!] 之前搜索一个空格或更多空格并将其替换为  

这是我的代码到目前为止适用于许多情况,除了:

hello[ SPACES ]?

应该是

hello ?

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

2 个答案:

答案 0 :(得分:0)

使用捕获组

对于一个或多个空格后跟 :?! 标记。捕获第二部分并在替换字符串中使用它。

const str = "Hey  ! Are you busy  ?";
str.replace(/ +([:?!])/g, " $1");
console.log(str);

答案 1 :(得分:0)

const str = '嗨,我的名字是 mahish dino' const k=str.replace(/\s/g, '`用任何字符串或整数替换这个空格') 控制台日志(k)

使用 str.replace(/\s/g, '') 方法可以用任何字符串替换空格。