日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
JavaScript中替換字符串的幾種方法

替換字符串中的文本是 JavaScript 開發(fā)中的常見任務(wù)。本文研究幾種用 replace 和正則表達(dá)式替換文本的方法。

創(chuàng)新互聯(lián)主要從事成都網(wǎng)站設(shè)計、做網(wǎng)站、網(wǎng)頁設(shè)計、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)永登,10年網(wǎng)站建設(shè)經(jīng)驗,價格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):13518219792

替換單個字串通常 JavaScript 的 String replace() 函數(shù)只會替換它在字符串中找到的第一個匹配的子符:

 
 
 
  1. const myMessage = 'this is the sentence to end all sentences'; 
  2. const newMessage = myMessage.replace('sentence', 'message'); 
  3. console.log(newMessage); // this is the message to end all sentences 

在這個例子中,僅替換了第一個 sentence 字串。

替換多個子串

如果希望 JavaScript 能夠替換所有子串,必須通過 /g 運算符使用正則表達(dá)式:

 
 
 
  1. const myMessage = 'this is the sentence to end all sentences'; 
  2. const newMessage = myMessage.replace(/sentence/g, 'message'); 
  3. console.log(newMessage); // this is the message to end all messages 

這一次次兩個子串都會被替換。

除了使用內(nèi)聯(lián) /g 之外,還可以使用 RegExp 對象的構(gòu)造函數(shù):

 
 
 
  1. const myMessage = 'this is the sentence to end all sentences'; 
  2. const newMessage = myMessage.replace(new RegExp('sentence', 'g'), 'message'); 
  3. console.log(newMessage); // this is the message to end all messages``` 

替換特殊字符

要替換特殊字符,例如 -/\^$*+?.()|[]{}),需要使用反斜杠對其轉(zhuǎn)義。

如果給定字符串 this\-is\-my\-url,要求把所有轉(zhuǎn)義的減號( \-)替換為未轉(zhuǎn)義的減號(-)。

可以用 replace() 做到:

 
 
 
  1. const myUrl = 'this\-is\-my\-url'; 
  2. const newUrl = myMessage.replace(/\\-/g, '-'); 
  3. console.log(newUrl); // this-is-my-url 

或者用new Regexp():

 
 
 
  1. const myUrl = 'this\-is\-my\-url'; 
  2. const newUrl = myUrl.replace(new RegExp('\-', 'g'), '-'); 
  3. console.log(newUrl); // this-is-my-url 

在第二個例子中不必用反斜杠來轉(zhuǎn)義反斜杠。


當(dāng)前名稱:JavaScript中替換字符串的幾種方法
網(wǎng)站地址:http://www.5511xx.com/article/cccehcj.html