Change character in string javascript

There are lot of answers here, and all of them are based on two methods:

  • METHOD1: split the string using two substrings and stuff the character between them
  • METHOD2: convert the string to character array, replace one array member and join it

Personally, I would use these two methods in different cases. Let me explain.

@FabioPhms: Your method was the one I initially used and I was afraid that it is bad on string with lots of characters. However, question is what's a lot of characters? I tested it on 10 "lorem ipsum" paragraphs and it took a few milliseconds. Then I tested it on 10 times larger string - there was really no big difference. Hm.

@vsync, @Cory Mawhorter: Your comments are unambiguous; however, again, what is a large string? I agree that for 32...100kb performance should better and one should use substring-variant for this one operation of character replacement.

But what will happen if I have to make quite a few replacements?

I needed to perform my own tests to prove what is faster in that case. Let's say we have an algorithm that will manipulate a relatively short string that consists of 1000 characters. We expect that in average each character in that string will be replaced ~100 times. So, the code to test something like this is:

var str = "... {A LARGE STRING HERE} ...";

for(var i=0; i<100000; i++)
{
  var n = '' + Math.floor(Math.random() * 10);
  var p = Math.floor(Math.random() * 1000);
  // replace character *n* on position *p*
}

I created a fiddle for this, and it's here. There are two tests, TEST1 (substring) and TEST2 (array conversion).

Results:

  • TEST1: 195ms
  • TEST2: 6ms

It seems that array conversion beats substring by 2 orders of magnitude! So - what the hell happened here???

What actually happens is that all operations in TEST2 are done on array itself, using assignment expression like strarr2[p] = n. Assignment is really fast compared to substring on a large string, and its clear that it's going to win.

So, it's all about choosing the right tool for the job. Again.

Examples

Replace Microsoft:

let text = "Visit Microsoft!";
let result = text.replace("Microsoft", "W3Schools");

Try it Yourself »

A global replacement:

let text = "Mr Blue has a blue house and a blue car";
let result = text.replace(/blue/g, "red");

Try it Yourself »

More examples below.


Definition and Usage

The replace() method searches a string for a value or a regular expression.

The replace() method returns a new string with the value(s) replaced.

The replace() method does not change the original string.


Note

If you replace a value, only the first instance will be replaced. To replace all instances, use a regular expression with the g modifier set.

Read more about regular expressions in our:

  • RegExp Tutorial
  • RegExp Reference


Syntax

string.replace(searchValue, newValue)

Parameters

Parameter Description
searchValue Required.
The value, or regular expression, to search for.
newValue Required.
The new value (to replace with).

Return Value

Type Description
A string A new string where the specified value(s) has been replaced.


More Examples

A global, case-insensitive replacement:

let text = "Mr Blue has a blue house and a blue car";
let result = text.replace(/blue/gi, "red");

Try it Yourself »

A function to return the replacement text:

let text = "Mr Blue has a blue house and a blue car";
let result = text.replace(/blue|house|car/gi, function (x) {
  return x.toUpperCase();
});

Try it Yourself »


Browser Support

replace() is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome IE Edge Firefox Safari Opera
Yes Yes Yes Yes Yes Yes


Topic: JavaScript / jQueryPrev|Next

Answer: Use the JavaScript replace() method

You can use the JavaScript replace() method to replace the occurrence of any character in a string. However, the replace() will only replace the first occurrence of the specified character. To replace all the occurrence you can use the global (g) modifier. The following example will show you how to replace all underscore (_) character in a string with hyphen (-).





JavaScript Replace Character in a String



    

quick_brown_fox


Here are some more FAQ related to this topic:

  • How to remove white space from a string using jQuery
  • How to find substring between the two words using jQuery
  • How to get substring from a string using jQuery

Can I change a character in a string JavaScript?

Javascript strings are immutable, they cannot be modified "in place" so you cannot modify a single character.

How do I replace a character in a string?

The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.

What is replace () in JavaScript?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

How do you change a string in JavaScript?

To replace text in a JavaScript string the replace() function is used. The replace() function takes two arguments, the substring to be replaced and the new string that will take its place. Regex(p) can also be used to replace text in a string.