Javascript Regular Expressions Reusing Groups of Characters

Introduction

You can reuse the pattern specified by a group of characters later on in the regular expression.

To refer to a previous group of characters, you just type \ and a number indicating the order of the group.

For example, you can refer to the first group as \1, the second as \2, and so on.

How can you find instances of repeated digits and replace them with the word ERROR?

You need to use the ability to refer to groups in regular expressions.

First, let's define the string as follows:

let myString  = "007,007,001,002,002,003,002,004"; 

Now you know you need to search for a series of one or more number characters.

In regular expressions the \d specifies any digit character, and + means one or more of the previous character. So far, that gives you this regular expression:

\d+ 

You want to match a series of digits followed by a comma, so you just add the comma:

\d+, 

The following defines a group whose pattern of characters is one or more digit characters.

This group must be followed by a comma and then by the same pattern of characters as in the first group.

Put this into some JavaScript, and you have the following:

let myString  = "007,007,001,002,002,003,002,004"; 
let myRegExp = /(\d+),\1/g; 
myString = myString.replace(myRegExp, "ERROR"); 
console.log(myString); /* w w  w.j a  v  a 2 s.  c  o m*/



PreviousNext

Related