0

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.

Maytham Fahmi
33.2k17 gold badges132 silver badges159 bronze badges
asked Dec 24, 2016 at 23:42
2
  • replace returns a new string. It does not modify the original. Commented Dec 24, 2016 at 23:51
  • so you want to replace string/chars by reference ? Commented Dec 25, 2016 at 0:16

3 Answers 3

6

You can use the following approach:

String.prototype.replaceAll = function(search, replacement) {
 return this.replace(new RegExp(search, 'g'), replacement);
};
answered Dec 24, 2016 at 23:46
Sign up to request clarification or add additional context in comments.

2 Comments

You don't even need a new variable, just use return this.replace(new RegExp(search, 'g'), replacement);
This is the same as 'abc'.replace(/a/g,'b');, except that it also invokes another function and creates a RegExp object.
1

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'));

answered Dec 25, 2016 at 0:24

Comments

1

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.

answered Dec 25, 2016 at 0:00

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.