[英]How can I write a replace method for String in JavaScript?
I heard, that string in JavaScript has immutability. 我听说,JavaScript中的字符串具有不变性。
So, how can I write a method to replace some character in string? 那么,如何编写替换字符串中某些字符的方法?
What I want is: 我想要的是:
String.prototype.replaceChar(char1, char2) {
for (var i = 0; i < this.length; i++) {
if (this[i] == char1) {
this[i] = char2;
}
}
return this;
}
Then, I can use it like this: 然后,我可以这样使用它:
'abc'.replaceChar('a','b'); // bbc
I know it will not work, because the immutability of string. 我知道这是行不通的,因为字符串不可更改。
But in native code, I can use the native replace method like this: 但是在本机代码中,我可以使用本机替换方法,如下所示:
'abc'.replace(/a/g,'b');
I don't really know how to solve this problem. 我真的不知道如何解决这个问题。
You can use the following approach: 您可以使用以下方法:
String.prototype.replaceAll = function(search, replacement) {
return this.replace(new RegExp(search, 'g'), replacement);
};
If you want a solution without regex (as a way to learn), you can use the following: 如果您想要不使用正则表达式的解决方案(作为一种学习方法),则可以使用以下方法:
String.prototype.replaceChar = function(char1, char2) { var s = this.toString(); for (var i = 0; i < s.length; i++) { if (s[i] == char1) { s = s.slice(0, i) + char2 + s.slice(i+1); } } return s; } console.log('aaabaaa'.replaceChar('a', 'c'))
The idea is that you need this content of the string in a temp variable, then you need to go char-by-char, and if that char is the one you are looking for - you need to build your string again. 这个想法是,您需要在temp变量中包含此字符串内容,然后需要逐个字符查找,如果该char是您要查找的字符,则需要再次构建字符串。
You can use array, too: 您也可以使用数组:
String.prototype.replaceChar = function (char1, char2) { newstr=[]; for (i = 0; i < this.length; i++) { newstr.push(this[i]); if (newstr[i] == char1) { newstr[i] = char2 } } return newstr.join(""); } console.log('abca'.replaceChar('a','G'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.