We can use JavaScript to replace multiple characters in a string by using the JavaScript String replace() method.

text.replace(/z|y/g, 'x');

In the code above, z and y are the characters we want to replace, and x is the character we will replace them with.


Let’s say we have the following HTML:

This sentence {has} some {braces} in {it}.

If we want to change the left and right brace characters and replace them with nothing, we can use our code above to do this using the replace() method.

var text = document.getElementById("p1").textContent;
text = text.replace(/{|}/g, '');
document.getElementById("p1").innerHTML = text;

Which would result in the following:

This sentence has some braces in it.

Using JavaScript to Replace All Numbers in a String

In this example, we will let the user input any text they want, and then replace any numbers in the text with nothing(''). We will then display the new text below. If there are no numbers in the text provided, no change will occur.

Here is the HTML setup.

Add text below with numbers in it.

Below is the JavaScript code which will take the user input using an onclick event and run the function below. The function will get the text using the getElementById method and textContent property, and use the replace() method on the text. We will then update the #results div using the textContent property.

Here is the JavaScript code:

function changeText() {
  var userText = document.getElementById("userVal").value;
  var replacedText = userText.replace(/0|1|2|3|4|5|6|7|8|9/g, '');
  document.getElementById("results").textContent = replacedText;
};

Notice in our JavaScript code above, the way we replace any number is with the following code:

userText.replace(/0|1|2|3|4|5|6|7|8|9/g, '');

We use the replace() method to replace multiple numbers at once with nothing.

The final code and output for this example of how to replace numbers in a string using JavaScript is below:

Code Output:

Add text below with numbers in it.


Full Code:

Add text below with numbers in it.

Hopefully this article has been useful for you to understand how to use JavaScript to replace multiple characters.

Categorized in:

JavaScript,

Last Update: March 12, 2024