replace方法用于字符串中的某些字符替換為其他字符,或替換與正則表達(dá)式匹配的子字符串,下面是JavaScript之replace方法的使用說明,跟著錯新技術(shù)頻道小編帶你來了解一下吧!
第一次發(fā)現(xiàn)JavaScript中replace()?方法如果直接用str.replace("-","!")?只會替換第一個匹配的字符.??
而str.replace(//-/g,"!")則可以替換掉全部匹配的字符(g為全局標(biāo)志)。??
replace()??
The?replace()?method?returns?the?string?that?results?when?you?replace?text?matching?its?first?argument??
(a?regular?expression)?with?the?text?of?the?second?argument?(a?string).??
If?the?g?(global)?flag?is?not?set?in?the?regular?expression?declaration,?this?method?replaces?only?the?first??
occurrence?of?the?pattern.?For?example,??
var?s?=?"Hello.?Regexps?are?fun.";s?=?s.replace(//./,?"!");?//?replace?first?period?with?an?exclamation?pointalert(s);?
produces?the?string?“Hello!?Regexps?are?fun.”?Including?the?g?flag?will?cause?the?interpreter?to??
perform?a?global?replace,?finding?and?replacing?every?matching?substring.?For?example,??
var?s?=?"Hello.?Regexps?are?fun.";s?=?s.replace(//./g,?"!");?//?replace?all?periods?with?exclamation?pointsalert(s);?
yields?this?result:?“Hello!?Regexps?are?fun!”??
上面是錯新技術(shù)頻道為大家整理的JavaScript之replace方法的使用說明,大家了解了多少呢?如大家有任何疑問可以給小編留言,這邊會在第一時間為大家解答。
新聞熱點(diǎn)
疑難解答
圖片精選