Home >Web Front-end >JS Tutorial >How to use replace function in js
The replace() function in JavaScript is used to find and replace the specified value in a string. The syntax is string.replace(searchValue, replaceValue), where searchValue is the value to be found, replaceValue is the replacement value, and the new string after replacement is returned. Optional regular expression flags can specify replacement behavior, such as global replacement (g), case-insensitive (i), or multi-line replacement (m).
Using the replace() function in JavaScript
Thereplace() function is used to find and replace strings the specified value. The syntax is as follows:
<code>string.replace(searchValue, replaceValue)</code>
where:
Usage:
replace() function returns a new string in which all substrings matching searchValue have been replaced by replaceValue. The original string is not modified.
Example:
<code>let str = "Hello, world!"; let newStr = str.replace("world", "JavaScript"); console.log(newStr); // 输出:"Hello, JavaScript!"</code>
Options:
replace() function can also use optional regular expression flags ( flags) to specify the replacement behavior:
Example:
<code>let str = "Hello, WORLD! Hello, world!"; let newStr = str.replace(/world/gi, "JavaScript"); console.log(newStr); // 输出:"Hello, JavaScript! Hello, JavaScript!"</code>
In the above example, the regular expression /world/g matches all instances of the "world" string (size-insensitive Write).
Other Notes:
The above is the detailed content of How to use replace function in js. For more information, please follow other related articles on the PHP Chinese website!