The searchValue parameter is required — the value, or regular expression, that will be replaced by the new value. The newValue parameter is required. It is the value on which we need to replace it with an original string.
// app.js let str = 'Alibaba is biggest tech company in china'; let res = str.replace('Alibaba', 'Tencent'); console.log(res);
Defining the regular expression in replace() method
We can also write the regular expression to change that string with a new string.
// app.js let str = 'Obama is a US president'; let newstr = str.replace(/Obama/i, 'Trump'); console.log(newstr);
Using global and ignore with replace()
Global replace can only be done with the regular expression.
// app.js let re = /bigbangtheory/gi; let str = 'The bigbangtheory is the best comedy show.'; let newstr = str.replace(re, 'friends'); console.log(newstr);
Switching words in a string
For the replacement text, the script uses the $1 and $2 replacement patterns.
// app.js let re = /(\w+)\s(\w+)/; let str = 'Krunal Lathiya'; let newstr = str.replace(re, '$2, $1'); console.log(newstr);
If you are replacing the value (and not a regular expression), only the first instance of the value will be replaced.