【问题标题】:Javascript string replace space with no-break space after a specific wordJavascript字符串在特定单词后用不间断空格替换空格
【发布时间】:2016-06-16 19:34:29
【问题描述】:

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

但是单词并不总是被空格包围 - 例如在这个句子中:

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

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

【问题讨论】:

    标签: javascript regex string replace


    【解决方案1】:

    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))
    );

    【讨论】:

    • 谢谢,完美运行。如何使用变量而不是“in”?我试过new RegExp("\b(" + preposition + ") ", "ig");,但它不起作用。
    • 使用构造函数是对的,只是反斜杠必须加倍:new RegExp("\\b(" + preposition + ") ", "ig");
    • 哦,我明白了 - 我必须转义反斜杠以使字符串文字表达“\b”,否则第一个反斜杠将转义“b”并且不会传递给构造函数。是真的吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多