replace method
The replace method searches
for and replaces parts of a string.
The first parameter is the substring
to be replaced with the substring
in the second parameter.
Syntax
javascriptstring.replace(what to replace, by what to replace);
Example
Let's replace 'ab' in
the string with '!':
javascriptlet str = 'abcde';
let newStr = str.replace('ab', '!');
console.log(newStr);
The code execution result:
javascript'!cde'
Example
Let's try to replace all matches in a string:
javascriptlet str = 'ab cde ab';
let newStr = str.replace('ab', '!');
console.log(newStr);
We see that the replacement occurred only on the first match:
javascript'! cde ab'
Example
Although the replace method
only changes the first match,
you can replace all matches
in a loop:
javascriptlet elem = 'ab';
let str = 'ab cde ab';
while (str.includes(elem)) {
str = str.replace(elem, '!');
}
console.log(str);
The code execution result:
javascript'! cde !'
See also
-
the
replacemethod
that searches and replaces parts of a string using regular expressions