Javascript Regular Expressions replace text

Introduction

Let's start by looking at an example in which you want to do a simple text replacement using the replace() method and a regular expression.

Imagine you have the following string:

let myString = "Paul, Paula, Pauline, paul, Paul"; 

and you want to replace any occurrence of the name "Paul" with "Ringo."

The pattern of text you need to look for is simply Paul.

Representing this as a regular expression, you have this:

let myRegExp = /Paul/; 

The forward-slash characters mark the start and end of the regular expression.

Now let's use this expression with the replace() method:

myString = myString.replace(myRegExp, "Ringo"); 

You can see that the replace() method takes two parameters: the RegExp object that defines the pattern to be searched and replaced, and the replacement text.

let myString = "Paul, Paula, Pauline, paul, Paul"; 
let myRegExp = /Paul/; 

myString = myString.replace(myRegExp, "Ringo"); 
console.log(myString); //from   ww  w . j  ava2s  . co m

You can see that this has replaced the first occurrence of Paul in your string.

By default, the RegExp object looks only for the first matching pattern.

The RegExp object has three attributes you can define, as listed in the following table:

Attribute Character
Description
g

Global match. This looks for all matches of the pattern rather than
stopping after the first match is found.
i

Pattern is case-insensitive. For example, Paul and paul are considered
the same pattern of characters.
i


Multi-line flag. This specifies that the special characters ^ and $ can
match the beginning and the end of lines as well as the beginning and
end of the string.

If you change the RegExp object in the code to the following, a global case-insensitive match will be made:

let myString = "Paul, Paula, Pauline, paul, Paul"; 
let myRegExp = /Paul/gi; 

myString = myString.replace(myRegExp, "Ringo"); 
console.log(myString); /* ww  w  . j  a  v a 2s  .  c o  m*/



PreviousNext

Related