javascript 中的replace方法

本文介绍了JavaScript中replace方法的基本使用方式,特别关注如何实现全局替换而非仅替换首次出现的匹配项。通过具体示例展示了如何利用正则表达式的g标志来达到这一目的,并解释了在字符串替换操作中使用转义字符的重要性。

第一次发现javascript中replace() 方法如果直接用str.replace("-","!") 只会替换第一个匹配的字符.

replace()
Thereplace()methodreturnsthestringthatresultswhenyoureplacetextmatchingitsfirstargument
(aregularexpression)
withthetextofthesecondargument(astring).
Iftheg(global)flagisnotset
intheregularexpressiondeclaration,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);

yields
thisresult:“Hello!Regexpsarefun!

我刚刚用它作了如下操作

把 |aaa|bbb|切换成,aaa,bbb,

replace(/\|/g, ",") 参数里边的/是用来转义的,\| 是能代表"|"么?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值