How to use replaceAll() method In Javascript

The JavaScript replaceAll() method returns a new string after replacing all the matches of a string with a specified string or a regular expression. The original string is left unchanged after this operation.

Syntax:

const newString = originalString.replaceAll(regexp | substr , newSubstr | function);

Example: In this example, we are using JavaScript replaceAll() method.

Javascript




// Input string
let origString = 'string / with some // slashes /';
// Display input string
console.log(origString);
 
// replacement cahracter
let replacementString = '*';
 
// Replace all slash using replaceAll method;
let replacedString =
            origString.replaceAll('/', '*');
 
// Display output
console.log(replacedString);


Output

string / with some // slashes /
string * with some ** slashes *


How to globally replace a forward slash in a JavaScript string ?

In JavaScript, a forward slash serves multiple purposes such as division operator, string character, etc. In this article, we will see how to globally replace a forward slash in a JavaScript string.

Below are the methods used to globally replace a forward slash in a JavaScript string:

Table of Content

  • Using replace() method with a regular expression.
  • Using the JavaScript split() method
  • Using JavaScript replaceAll() method

Similar Reads

Method 1: Using replace() method with a regular expression.

The replace() method searches a string for a specified value or expression, replacing it with a new value. The original string remains unchanged. To replace all forward slashes, a regular expression is used. The forward slash (/) is a special character in regex, necessitating escape with a backward slash (). The global modifier (g) in the regular expression ensures the replacement of all occurrences of forward slashes in the given string. Importantly, the replace() method does not modify the original string; it returns a new string with replacements....

Method 2: Using the JavaScript split() method

...

Method 3: Using JavaScript replaceAll() method

The split() method breaks a string into parts using a chosen separator, such as the forward slash. This creates an array of strings based on where the slashes were. The join() method then combines an array of strings back into one. By specifying a new character as a parameter, it replaces all the original forward slashes in the initial string. Together, split() and join() offer a straightforward way to replace specific characters, like the forward slash, in a given string. It’s crucial to note that these operations don’t change the original string; instead, they produce a new string with the desired modifications....