This article demonstrates how to use the replace() function in javascript with regular expressions using different examples of replacing characters from a string.

Table of Contents:

Introduction and Syntax of replace() function

Javascript’s replace() method replaces a particular pattern in the javascript with a replacement. The pattern can be a regular expression, a function, or a string.

Argument1:– This is the pattern to be found and replaced within the calling string.

Argument2: This is the replacement, it can be a character or a string.

Syntax:-

replace(pattern, replacement)

Example1: Replace special characters from a string

Replace special characters from “Javascript123 #* Is The &^ Most Popular Language

Code:-

let dummyString = "Javascript123  #* Is The &^  Most Popular  Language";
dummyString = dummyString.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
console.log(dummyString);

Output:-

Javascript123   Is The   Most Popular  Language

Explanation:-

  • Here in the above code replace() function is used. The Regular expression is /[`~!@#$%^&*()_|+-=?;:'”,.<>{}[]\\/]/g
  • /and / marks the beginning and end of a pattern.
  • [ ] finds the characters within the brackets
  • `~!@#$%^&*()_|+-=?;:'”,.<>{}[]\\/ matches these special characters within the string.
  • g specifies to match all occurrences of the pattern within the string.

Example2: Replace spaces from a string

Replace spaces from “Javascript123 #* Is The &^ Most Popular Language

Code:-

let dummyString = "Javascript123  #* Is The &^  Most Popular  Language";
dummyString = dummyString.replace(/\s+/g, '');
console.log(dummyString);

Output:-

Javascript123#*IsThe&^MostPopularLanguage

Explanation:-

  • The Regular expression is /\s+/g
  • /and / marks the beginning and end of a pattern.
  • \s+ matches at least one space character within the string.
  • g specifies to match all occurrences of the pattern within the string.

Example3: Replace anything but digits from a string

Replace other characters except digits from “Javascript123 #* Is The &^ Most Popular Language”

Code:-

let dummyString = "Javascript123  #* Is The &^  Most Popular  Language";
dummyString = dummyString.replace(/[^0-9]/g,'');
console.log(dummyString);

Output:-

123

Explanation:-

  • The Regular expression is /[^0-9]/g
  • /and / marks the beginning and end of a pattern.
  • [^0-9] matches all characters except digits within the string.
  • g specifies to match all occurrences of the pattern within the string.

Read More:

I hope this article helped you to understand the usage of replace() function with regex. Good Luck!!!