I heard, that string in JavaScript has immutability.
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.
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'));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.