How to Replace Characters in a String with JavaScript replace() | Plantpot

How to Replace Character in a String with JavaScript replace()

Web Dev
Sponsored links

In this article, I will introduce how to replace character in a string with JavaScript replace().

The replace() method

The replace() method replaces a specific character in a string with another.
Depending on the program you want to create, you may want to replace a specific character contained in a string with another character.
Use the replace() method when you want to replace a specific character contained in a string with another character.
You can also replace various patterns by using a replacement rule called a regular expression.

The syntax is below.

string.replace(regexp, newSubstr[, flag])

※Since "flag" is not normally used, it is omitted.

Sponsored links

Replace characters in a string

Below is a sample that replaces the character in the string.

let str = "I like football.";
let newstr = str.replace("football", "baseball");
console.log(str); 
console.log(newstr);

//result
//"I like football."
//"I like baseball."

The variable "str" ​​is prepared, and the result of replacing the character "football" with "baseball" in replace is put in the variable "newstr".
The specified character is replaced with the character to be replaced.
As a result, the string "I like baseball." is output.