【问题标题】:Replacing a word with another word without replacing another word which contains a similar substring in the same sentence in Javascript在Javascript中用另一个词替换一个词而不替换另一个在同一个句子中包含相似子字符串的词
【发布时间】:2021-10-02 04:08:52
【问题描述】:

我正在尝试用另一个词替换一个词,特别是用“had”替换“has”。但是该字符串包含具有子字符串“has”的单词“hash”,因此它也会被替换。我该怎么做才能解决这个问题?

function replace() {
    sentence = sentence.replaceAll("has", "had");
}

【问题讨论】:

  • 解决这个问题的一种简单方法是将' has '(前后有空格)替换为' had '。一个可能更好的方法是使用 replace() 和像 /\bhas\b/g 这样的正则表达式。

标签: javascript string replace substring replaceall


【解决方案1】:

在要替换的单词周围放置单词边界:

var input = "A man who has an appetite ate hashed browns";
var output = input.replace(/\bhas\b/g, "had");
console.log(output);

请注意,我使用了常规的 replace 以及 /g 全局标志。这应该与使用 replaceAll 具有相同的行为。

【讨论】:

    猜你喜欢
    • 2019-09-24
    • 2012-02-26
    • 2021-07-22
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多