js替換函數用法


定義和用法

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM