Javascript 正则表达式:替换之前的espaces:!?与&;nbsp;如果它不存在

Javascript 正则表达式:替换之前的espaces:!?与&;nbsp;如果它不存在,javascript,regex,Javascript,Regex,如果不存在空格,我想将其替换为: input: "hello!", expect: "hello&nbsp!;" input: "hello !", expect: "hello&nbsp!;" input: "hello !", expect: "hello&nbsp!;" input: "hello !", e

如果不存在空格,我想将其替换为

input: "hello!", expect: "hello&nbsp!;"
input: "hello !", expect: "hello&nbsp!;"
input: "hello  !", expect: "hello&nbsp!;"
input: "hello !", expect: "hello&nbsp!"
最后一行,我得到了

input: "hello !", expect: "hello  !"
它增加了一个额外的
,我想避免它

以下是我目前的代码:

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

您可以通过在空格和标点之前匹配可选的
s并在替换中丢弃它们来完成此操作:

const strs=[
“你好!”,
“你好!”,
“你好!”,
“你好!”,
“你好!”,
“你好!”
];
console.log(strs.map(s=>s.replace(/(?:)**([:!?])/,“$1”))
使用

。替换(/(?:|\s)*([:!?])/,“$1”)

解释

--------------------------------------------------------------------------------
(?:组,但不捕获(0次或更多次)
(匹配尽可能多的金额):
--------------------------------------------------------------------------------
' '
--------------------------------------------------------------------------------
|或
--------------------------------------------------------------------------------
\s空格(\n、\r、\t、\f和“”)
--------------------------------------------------------------------------------
)*分组结束
--------------------------------------------------------------------------------
(组和捕获到\1:
--------------------------------------------------------------------------------
[:!?]以下任意字符:':','!','?'
--------------------------------------------------------------------------------
)结束\1
Javascript代码
const strs=[
“你好!”,
“你好!”,
“你好!”,
“你好!”,
“你好!”,
“你好!”
];

console.log(strs.map(s=>s.replace(/(?:|\s)*([:!?])/,“$1”)
这种替换通常分两步完成:首先按现在的方式进行替换,然后删除重复项(仅用一个替换两个
)。它也可以在一个步骤中完成,使用包含断言的正则表达式,但这种方法更简单。