定義和用法
replace() 方法用於在字符串中用一些字符替換另一些字符,或替換一個與正則表達式匹配的子串。
語法
stringObject.replace(regexp/substr,replacement)
實例
例子 1
在本例中,我們將使用 "W3School" 替換字符串中的 "Microsoft":
<script type="text/javascript">
var str="Visit Microsoft!"
document.write(str.replace(/Microsoft/, "W3School")
)
</script>
輸出:
Visit W3School!
例子 2
在本例中,我們將執行一次全局替換,每當 "Microsoft" 被找到,它就被替換為 "W3School":
<script type="text/javascript">
var str="Welcome to Microsoft! "
str=str + "We are proud to announce that Microsoft has "
str=str + "one of the largest Web Developers sites in the world."
document.write(str.replace(/Microsoft/g, "W3School")
)
</script>
輸出:
Welcome to W3School! We are proud to announce that W3School has one of the largest Web Developers sites in the world.
參考:
http://www.w3school.com.cn/jsref/jsref_replace.asp
原文地址:
https://www.cnblogs.com/poterliu/p/11009330.html