gpt4 book ai didi

Javascript字符串在特定单词后用不间断空格替换空格

转载 作者:行者123 更新时间:2023-11-30 11:56:15 35 4
gpt4 key购买 nike

我有一个特定的词(例如“in”),我想用一个不间断的空格替换后面的一个空格。我使用普通替换:从 "in " to "in"+ String.fromCharCode(160).

然而单词并不总是被空格包围——例如在这句话中:

这是示例文本(,其中有括号)。

所以我需要一个正则表达式来用不间断的空格替换 "in" 之后的空格。我该怎么做?

最佳答案

您可以在 in 之前使用单词边界

.replace(/\bin /g, "in" + String.fromCharCode(160))

让它不区分大小写:

.replace(/\b(in) /ig, "$1" + String.fromCharCode(160))

这里是 the regex demo

请看下面的演示:

console.log(
"In this is sample text (in which there are parentheses)."
.replace(/\b(in) /ig, "$1" + String.fromCharCode(160))
);

关于Javascript字符串在特定单词后用不间断空格替换空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37867952/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com