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提供了一种可以为您做到这一点的方法 !