【发布时间】: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