gpt4 book ai didi

javascript - 如何更改替换功能中的所有单词

转载 作者:行者123 更新时间:2023-11-28 16:46:55 24 4
gpt4 key购买 nike

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

今天我想我的问题终于不是太复杂了

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

我的问题如下,我用“W3Schools”替换“Microsoft”,它工作正常,只是我必须双击“尝试一下”将 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>

最佳答案

你可以使用这个:

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

/Microsoft/g - 其中 g - 表示全局替换在字符串中找到 Microsoft 的位置,并将其替换为 W3Schools

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

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

关于javascript - 如何更改替换功能中的所有单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60451932/

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