How to use JavaScript String replace()

Program to use JavaScript String replace() method


let a = 'My Car is Blue';

console.log("data =", a);

let b = a.replace('Blue', 'Red');

console.log("replace data =",b);

Output


data = My Car is Blue
replace data = My Car is Red

Steps Description

  1. Declare two variable a and b
  2. Initialize two variable with value of string a = 'My Car is Blue' and b = a.replace('Blue', 'Red')
  3. replace() method if a word or character is found in the string after searching, then it works to replace that word or character with another word or character.
  4. The value of a variables and b variables is displayed with the help of console.log inbuilt function

Program to use JavaScript String replace() method


let c = 'My favorite Color Green laptop Color Green bag Color Green';

console.log("data =", c);


let d = c.replace(/Green/g, "Yellow");

console.log("replace data =",d);

Output


data = My favorite Color Green laptop Color Green bag Color Green
replace data = My favorite Color Yellow laptop Color Yellow bag Color Yellow

Steps Description

  1. Declare two variable c and d
  2. Initialize two variable with value of string c = 'My favorite Color Green laptop Color Green bag Color Green' and d = c.replace(/Green/g, "Yellow")
  3. replace() method if a word or character is found in the string after searching, then it works to replace that word or character with another word or character.
  4. The value of c variables and d variables is displayed with the help of console.log inbuilt function