【问题标题】:How to change all words in Replace function如何更改替换功能中的所有单词
【发布时间】:2020-02-28 12:41:35
【问题描述】:

我想解释一下我今天遇到的问题。

今天我觉得我的问题终于不是太复杂了我希望

在下面的代码中, 我正在寻找使用“替换”功能

我的问题如下, 我将“Microsoft”替换为“W3Schools”, 它工作正常,除了我必须双击“试试” 将 Word 更改两次“Microsoft”。

所以我宁愿改变所有的词 "Microsoft" , 一键搞定

您知道如何解决这个问题吗?内夫

<p id="demo">Visit Microsoft! Visit Microsoft!</p>
<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
var str = document.getElementById("demo").innerHTML; 
var res = str.replace("Microsoft", "W3Schools");
document.getElementById("demo").innerHTML = res;
}
</script>

【问题讨论】:

  • 使用带有全局 (g) 标志的正则表达式 - str.replace(/Microsoft/g, 'W3Schools');
  • 您需要使用带有全局标志的正则表达式变体.. -> 'Visit Microsoft! Visit Microsoft!'.replace(/Microsoft/g,'W3Schools')
  • 你可以使用正则表达式str.replace(/Microsoft/g,'W3school')
  • @fubar /Keith /Mohit Karkar,谢谢

标签: javascript function methods


【解决方案1】:

你可以用这个:

str.replace("/Microsoft/g", "W3Schools");

/Microsoft/g - 其中 g - 表示全局替换它在用 W3Schools 替换的字符串中找到 Microsoft 的位置

为了不区分大小写,你应该使用 gi 而不是 g

str.replace("/Microsoft/gi", "W3Schools");

【讨论】:

    【解决方案2】:

    尝试使用正则表达式

    var res = str.replace(/Microsoft/g, "W3Schools");
    

    而不是

    var res = str.replace("Microsoft", "W3Schools");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      相关资源
      最近更新 更多