📜  replaceall nodejs - Javascript (1)

📅  最后修改于: 2023-12-03 14:47:03.966000             🧑  作者: Mango

replaceAll in Node.js / JavaScript

Introduction

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.

Syntax

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.
Examples
Example 1: Replacing All Occurrences of a Substring
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!
Example 2: Case-Insensitive Replacement
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!
Example 3: Replacing with Regular Expression
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
Remarks
  • The replaceAll function is available in Node.js starting from version 15.0.0 and in most modern web browsers.
  • The searchValue parameter can be either a string or a regular expression.
  • If a regular expression is used for searchValue, it can include the g (global) and i (case-insensitive) flags for advanced matching.
  • If the searchValue is not found in the original string, the returned string will be unchanged.
Conclusion

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.