June 1, 2023
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
andb
- Initialize two variable with value of string
a = 'My Car is Blue'
andb = 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 andb
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
- Declare two variable
c
andd
- Initialize two variable with value of string
c = 'My favorite Color Green laptop Color Green bag Color Green'
andd = 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 andd
variables is displayed with the help of console.log inbuilt function
by : Suhel Akhtar
Quick Summary:
JavaScript String replace() method example