Reputation: 487
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.
Upvotes: 0
Views: 173
Reputation: 5162
You can use the following approach:
String.prototype.replaceAll = function(search, replacement) {
return this.replace(new RegExp(search, 'g'), replacement);
};
Upvotes: 6
Reputation: 11328
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'));
Upvotes: 1
Reputation: 62566
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.
Upvotes: 1