replace method
The replace
method searches
for and replaces parts of a string.
The first parameter is
regular expression,
and the second is the substring
to replace with.
Syntax
string.replace(regex, replacement);
Example
Let's find and replace the
character 'a'
:
let str = 'bab';
let res = str.replace(/a/, '!');
console.log(res);
The code execution result:
'b!b'
Example
By default, only the first match is
replaced. Let's replace the character
'a'
in the string again:
let str = 'baaab';
let res = str.replace(/a/, '!');
console.log(res);
The code execution result:
'b!aab'
Example
Let's replace all matches with a global search:
let str = 'baaab';
let res = str.replace(/a/g, '!');
console.log(res);
The code execution result:
'b!!!b'
Example
Let's find and replace a string with
this pattern: letter 'x'
,
then any character, then again
letter 'x'
:
let str = 'xax eee';
let res = str.replace(/x.x/, '!');
console.log(res);
The code execution result:
'! eee'
See also
-
the
replace
method
that searches for and replaces parts of a string -
the
test
method
that checks a string -
the
match
method
that searches for matches in a string -
the
matchAll
method
that searches for all matches in a string -
the
exec
method
that performs a sequential search -
the
search
method
that performs a search -
the
split
method
that splits a string