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); |
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