JavaScript 中的replace方法说明
2018-09-24 21:52
第一次发现JavaScript中replace()方法如果直接用str.replace("-","!")只会替换第一个匹配的字符.
而str.replace(/\-/g,"!")则可以替换掉全部匹配的字符(g为全局标志)。
replace()
Thereplace()methodreturnsthestringthatresultswhenyoureplacetextmatchingitsfirstargument
(aregularexpression)withthetextofthesecondargument(astring).
Iftheg(global)flagisnotsetintheregularexpressiondeclaration,thismethodreplacesonlythefirst
occurrenceofthepattern.Forexample,
vars="Hello.Regexpsarefun.";s=s.replace(/\./,"!");//replacefirstperiodwithanexclamationpointalert(s);
producesthestring“Hello!Regexpsarefun.”Includingthegflagwillcausetheinterpreterto
performaglobalreplace,findingandreplacingeverymatchingsubstring.Forexample,
vars="Hello.Regexpsarefun.";s=s.replace(/\./g,"!");//replaceallperiodswithexclamationpointsalert(s);
yieldsthisresult:“Hello!Regexpsarefun!”
文章标题:JavaScript 中的replace方法说明
文章链接:http://soscw.com/index.php/essay/17775.html