Home >Web Front-end >JS Tutorial >How to use replace in js

How to use replace in js

下次还敢
下次还敢Original
2024-05-01 03:51:18531browse

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.

How to use replace in js

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

  • replaceWhat: Character or subtitle to find string.
  • replaceWith: The character or substring to be replaced.
  • count (optional): The number of times to replace (default is all).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What does nan mean in jsNext article:What does nan mean in js