【发布时间】:2016-06-16 19:34:29
【问题描述】:
我有特定的单词(例如“in”),之后我想用不间断空格替换空格。我使用普通替换:从 " in " 到 " in" + String.fromCharCode(160)。
但是单词并不总是被空格包围 - 例如在这个句子中:
这是示例文本(在中有括号)。
所以我需要一个正则表达式来用不间断空格替换 "in" 之后的空格。我该怎么做?
【问题讨论】:
标签: javascript regex string replace
我有特定的单词(例如“in”),之后我想用不间断空格替换空格。我使用普通替换:从 " in " 到 " in" + String.fromCharCode(160)。
但是单词并不总是被空格包围 - 例如在这个句子中:
这是示例文本(在中有括号)。
所以我需要一个正则表达式来用不间断空格替换 "in" 之后的空格。我该怎么做?
【问题讨论】:
标签: javascript regex string replace
in之前可以使用单词边界
.replace(/\bin /g, "in" + String.fromCharCode(160))
使其不区分大小写:
.replace(/\b(in) /ig, "$1" + String.fromCharCode(160))
请看下面的演示:
console.log(
"In this is sample text (in which there are parentheses)."
.replace(/\b(in) /ig, "$1" + String.fromCharCode(160))
);
【讨论】:
new RegExp("\b(" + preposition + ") ", "ig");,但它不起作用。
new RegExp("\\b(" + preposition + ") ", "ig");