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

How to use replace in js

下次还敢
Release: 2024-05-01 03:51:18
Original
627 people have browsed it

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

string.replace(replaceWhat, replaceWith[, count]);
Copy after login

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:

let str = "Hello World";
str.replace("World", "Universe"); // "Hello Universe"
Copy after login

2. Regular expression replacement

Find and replace substrings using regular expressions:

let str = "This is a test sentence.";
str.replace(/\s/g, "-"); // "This-is-a-test-sentence."
Copy after login

3. Partial replacement

Limit the number of times to be replaced:

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."
Copy after login

4. Find and replace function

Use the callback function to specify the replacement content:

let str = "John Doe";
str.replace(/(?<name>\w+) (?<surname>\w+)/, match => `${match.groups.surname}, ${match.groups.name}`); // "Doe, John"
Copy after login

5. Global replacement

g flag globally matches and replaces all matching substrings:

let str = "The lazy dog jumped over the lazy fox.";
str.replace(/lazy/g, "quick"); // "The quick dog jumped over the quick fox."
Copy after login

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 of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template