String replace()
str.replace(search, replacement)
str
is a stringreplace
is function namesearch
is a string or regular expressionreplacement
is a string
replace() method replaces the first occurrence of search
string or regular expression with the replacement
string in the string str
, and returns the resulting string. replace() method does not modify the original string
Examples
1. replace the string 'banana'
with the string 'mango'
in str
let str = 'apple banana cherry banana cherry';
let output = str.replace('banana', 'mango');
console.log(output);
2. replace the string that matches the 'banana'
case insensitive with 'mango'
let str = 'apple BANANA cherry banana cherry';
let output = str.replace(/banana/i, 'mango');
console.log(output);