替换JavaScript中所有出现的字符串

One thing you may have noticed is that JavaScript's String.replace() method doesn't act like replacement methods in other languages. Take the following for example:

您可能已经注意到的一件事是JavaScript的String.replace()方法不像其他语言中的替换方法那样起作用。 以以下为例:


var replaced = 'The MooTools JavaScript library is is great.  I have never loved any code as I have MooTools!'.replace('MooTools','MooTools FTW!');


The above code will only replace the first occurrence of "MooTools" -- not every occurrence like PHP's str_replace() would. To replace every occurrence of a string in JavaScript, you must provide the replace() method a regular expression with a global modifier as the first parameter:

上面的代码将仅替换“ MooTools”的第一次出现-并非像PHP的str_replace()那样每次出现。 要替换JavaScript中每次出现的字符串,必须为replace()方法提供一个带有全局修饰符作为第一个参数的正则表达式:


var replaced = 'The MooTools JavaScript library is is great.  I have never loved any code as I have MooTools!'.replace(/MooTools/g,'MooTools FTW!');


Remember that you must escape special characters within your regular expression. And oh -- how convenient! MooTools provides a method that will do that for you!

请记住,您必须在正则表达式中转义特殊字符。 哦-多么方便! MooTools提供了一种可以为您做到这一点的方法

翻译自: https://davidwalsh.name/javascript-replace

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值