JS中用replace的问题

"hand hand hand"想变换为"hand.gif hand.gif hand.gif"
开始用
str=str.replace("hand","hand.gif");
输出:hand.gif hand hand
只替换了一次。。。:(
想到用正则,因为replace本来就可以用正则替换。

引用

返回根据正则表达式进行文字替换后的字符串的复制。

stringObj.replace(rgExp, replaceText)


于是写
str = str.replace(/hand/,"hand.gif")
无效。。。
全部替换要加g,
str = str.replace(/hand/g,"hand.gif")
还是不行:(

参考了
JavaScript的replace方法与正则表达式结合应用讲解 这篇文章后,终于明白,原来要用()括起来,才会替换()里的东东。正确的写法如下:
str = "hand hand hand";
str=str.replace(/(hand)/g,"hand.gif");   
document.write(str);  
正确输出:hand.gif hand.gif hand.gif。

JS的正则另一种写法是使用RegExp:
如str=str.replace(/(hand)/g,"hand.gif");
等同于:
reg = new RegExp("(hand)","g");
    str = str.replace(reg,'hand.gif');
reg需要动态生成时更适合使用这种方式。

扩展一下:
str = "hand'( hand'( hand'(";
str=str.replace(/(hand/'/()/g,"hand.gif");   
document.write(str);

str = 'hand/'( hand/'( hand/'(';
str=str.replace(/(hand/'/()/g,"hand.gif");   
document.write(str);    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值