Home >Web Front-end >JS Tutorial >How to use replace in js
The replace() method in JavaScript is used to find and replace specified characters or substrings in a string. The usage is: string.replace(replaceWhat, replaceWith[, count]). It can perform operations such as string replacement, regular expression replacement, partial replacement, find and replace functions, and global replacement.
Usage of replace() in JavaScript
What is replace()?
replace() method is used to find and replace specified characters or substrings in a string.
Usage
<code class="javascript">string.replace(replaceWhat, replaceWith[, count]);</code>
Parameters
Return value
Returns the replaced string without modifying the original string.
Detailed usage
1. String replacement
Replace the specified character with another character:
<code class="javascript">let str = "Hello World"; str.replace("World", "Universe"); // "Hello Universe"</code>
2. Regular expression replacement
Find and replace substrings using regular expressions:
<code class="javascript">let str = "This is a test sentence."; str.replace(/\s/g, "-"); // "This-is-a-test-sentence."</code>
3. Partial replacement
Limit the number of times to be replaced:
<code class="javascript">let str = "The quick brown fox jumps over the lazy dog."; str.replace("the", "a", 1); // "The quick brown fox jumps over a lazy dog."</code>
4. Find and replace function
Use the callback function to specify the replacement content:
<code class="javascript">let str = "John Doe"; str.replace(/(?<name>\w+) (?<surname>\w+)/, match => `${match.groups.surname}, ${match.groups.name}`); // "Doe, John"</code>
5. Global replacement
g
flag globally matches and replaces all matching substrings:
<code class="javascript">let str = "The lazy dog jumped over the lazy fox."; str.replace(/lazy/g, "quick"); // "The quick dog jumped over the quick fox."</code>
The above is the detailed content of How to use replace in js. For more information, please follow other related articles on the PHP Chinese website!