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

01/26/2022

Contents

In this article, you will learn 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.

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.