JavaScript 中的replace方法说明_Javascript教程-查字典教程网
JavaScript 中的replace方法说明
JavaScript 中的replace方法说明
发布时间:2016-12-30 来源:查字典编辑
摘要:第一次发现JavaScript中replace()方法如果直接用str.replace("-","!")只会替换第一个匹配的字符.而str....

第一次发现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教程学习
    热门Javascript教程学习
    编程开发子分类