我听说,JavaScript中的字符串具有不变性.
那么,我怎样才能编写一个方法来替换字符串中的某些字符?
我想要的是:
String.prototype.replaceChar(char1, char2) {
for (var i = 0; i < this.length; i++) {
if (this[i] == char1) {
this[i] = char2;
}
}
return this;
}
Run Code Online (Sandbox Code Playgroud)
然后,我可以像这样使用它:
'abc'.replaceChar('a','b'); // bbc
Run Code Online (Sandbox Code Playgroud)
我知道它不会起作用,因为字符串的不变性.
但在本机代码中,我可以使用这样的本机替换方法:
'abc'.replace(/a/g,'b');
Run Code Online (Sandbox Code Playgroud)
我真的不知道如何解决这个问题.
您可以使用以下方法:
String.prototype.replaceAll = function(search, replacement) {
return this.replace(new RegExp(search, 'g'), replacement);
};
Run Code Online (Sandbox Code Playgroud)