JS中实现replaceAll的方法

本文详细介绍了JavaScript中的replace方法,特别是如何使用正则表达式的全局标志(g)来替换字符串中的所有匹配项,而不是仅替换首次出现的匹配项。文中通过示例展示了不同使用方式的效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一次发现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!”

所以可以用以下几种方式.:
string.replace(/reallyDo/g,replaceWith);
string.replace(newRegExp(reallyDo,'g'),replaceWith);

string:字符串表达式包含要替代的子字符串。
reallyDo:被搜索的子字符串。
replaceWith:用于替换的子字符串。

Js代码收藏代码
  1. <scripttype="text/javascript">
  2. String.prototype.replaceAll=function(reallyDo,replaceWith,ignoreCase){
  3. if(!RegExp.prototype.isPrototypeOf(reallyDo)){
  4. returnthis.replace(newRegExp(reallyDo,(ignoreCase?"gi":"g")),replaceWith);
  5. }else{
  6. returnthis.replace(reallyDo,replaceWith);
  7. }
  8. }
  9. </script>


原文 :http://fuleonardo.iteye.com/blog/339749

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值