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
string.replace(what to replace, by what to replace);
Example
Let's replace 'ab'
in
the string with '!'
:
let str = 'abcde';
let newStr = str.replace('ab', '!');
console.log(newStr);
The code execution result:
'!cde'
Example
Let's try to replace all matches in a string:
let str = 'ab cde ab';
let newStr = str.replace('ab', '!');
console.log(newStr);
We see that the replacement occurred only on the first match:
'! cde ab'
Example
Although the replace
method
only changes the first match,
you can replace all matches
in a loop:
let elem = 'ab';
let str = 'ab cde ab';
while (str.includes(elem)) {
str = str.replace(elem, '!');
}
console.log(str);
The code execution result:
'! cde !'
See also
-
the
replace
method
that searches and replaces parts of a string using regular expressions