How to use JavaScript String replace()
String replace
On this page
String replace() method
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
- Declare two variable a and b
- Initialize two variable with value of string a = ‘My Car is Blue’ and b = a.replace(‘Blue’, ‘Red’)
- 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.
- The value of a variables and b variables is displayed with the help of console.log inbuilt function
String replace() method
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
- Declare two variable c and d
- 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”)
- 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.
- The value of c variables and d variables is displayed with the help of console.log inbuilt function