📅  最后修改于: 2023-12-03 14:47:03.966000             🧑  作者: Mango
The replaceAll
function is a useful utility in Node.js/JavaScript that allows for replacing all occurrences of a substring within a given string. It serves as a handy alternative to the replace
method, which only replaces the first occurrence.
In this guide, we will explore how to use the replaceAll
function in Node.js/JavaScript, providing code examples and explanations along the way.
The syntax for using the replaceAll
function is as follows:
str.replaceAll(searchValue, replaceValue);
str
: The original string in which replacements need to be made.searchValue
: The substring that needs to be replaced.replaceValue
: The replacement string for searchValue
.const originalString = 'Hello World! Hello JavaScript!';
const searchString = 'Hello';
const replaceString = 'Hi';
const replacedString = originalString.replaceAll(searchString, replaceString);
console.log(replacedString);
Output:
Hi World! Hi JavaScript!
const originalString = 'Hello World! HELLO JavaScript!';
const searchString = /hello/gi;
const replaceString = 'Hi';
const replacedString = originalString.replaceAll(searchString, replaceString);
console.log(replacedString);
Output:
Hi World! Hi JavaScript!
const originalString = 'The quick brown fox jumps over the lazy dog';
const searchString = /[aeiou]/g;
const replaceString = 'X';
const replacedString = originalString.replaceAll(searchString, replaceString);
console.log(replacedString);
Output:
ThX qXck brXwn fXx jXmps XvXr thX lXzy dXg
replaceAll
function is available in Node.js starting from version 15.0.0 and in most modern web browsers.searchValue
parameter can be either a string or a regular expression.searchValue
, it can include the g
(global) and i
(case-insensitive) flags for advanced matching.searchValue
is not found in the original string, the returned string will be unchanged.The replaceAll
function in Node.js/JavaScript provides a convenient way to replace all occurrences of a substring within a given string. It offers more flexibility than the standard replace
method, making it easier to perform complex replacements. Whether you need to replace simple substrings or use regular expressions, replaceAll
can help you achieve your desired results.