How to work on JavaScript with RegExp?

Reading Time: 4 minutes

What Are Regular Expressions?

This is a sequence of characters used to match character combinations in strings for text matching/searching. Regular expressions in javascript are search patterns (JavaScript objects) from sequences of characters. RegExp makes searching and matching strings easier and faster.

How to Create RegExp Objects in JavaScript?

Regular expressions in JavaScript are created with the RegExp object.

Literal Notation

Literal notation is one method of creating RegExp objects in JavaScript. This method involves the use of RegExp literal syntax. RegExp literal notation consists of the enclosing of your expression in slashes / without the use of quotation marks.

The code below shows the syntax for using the literal notation when creating JavaScript regular expressions:

let re = "Hello Studytonight";
let result1 = /hello/.test(re);
console.log(result1);      // false
let result2 = /hello/i.test(re);
console.log(result2);      // true

What the command above does, is search for hello in the String Hello Studytonight. Also, we can perform a case insensitive search with i the flag that will ignore case sensitivity.

Constructor Function

Another way developers can create regular expressions in JavaScript is using a constructor. This method takes in regular expressions as Strings in function arguments. Below is an example with syntax to create JS regular expression with a constructor:

let str = "Hello Studytonight";
let regex1 = new RegExp('hello');
console.log(regex1.test(str));  // false
let regex2 = new RegExp('hello', 'i');
console.log(regex2.test(str));  // true

Regular Expression Methods

JavaScript has different methods to work on regular expression. We will discuss this in detail below.

1. exec()

Method exec() executes a search and returns an array of results or a null. It can be used for iteration over multiple matches in a string of text. For instance, we’ll look at the example below with and without iteration utilizing the exec() method.

//without iteration
let regex1 = RegExp('fam*', 'g');
let str1 = 'make family everything familiar';

str1 = regex1.exec(str1);
console.log(str1); //output fam, index:5

//with iteration
const regex1 = RegExp('fam*', 'g');
const str1 = 'make family everything familiar';
let array1;

while ((array1 = regex1.exec(str1)) !== null) {
  console.log(`Found ${array1[0]}. Next starts at ${regex1.lastIndex}.`);
  // outputs "Found fam. Next starts at 8."
  // outputs "Found fam. Next starts at 26."
}

Notice that without iteration, we get the index of the first match only. With iteration, we get results of all (multiple) matches.

This RegExp method searches for a match between a regular expression and a String. It returns true or false if a match is found or not. With this method, you can also use the global flag g. Let’s look at an example, to search for a regular expression in a String, with and without the global flag g.

const str = 'in a space of time spark';
const regex = new RegExp('spa');
console.log(regex.test(str));
//output: true

With test() method, you can also use the global flag ‘g'. Below is an example:

const str = 'in a space of time spark';
const globalRegex = new RegExp('spa', 'g');
console.log(globalRegex.test(str));
// output: true

However, the global flag can allow us to iterate in our search to determine how many times spa is present in the String. We can also determine the index of the different positions that spa can be found in our String. This can’t be achieved without the global flag, as the test() method will run through the String, determining if our expression (spa) is present or not, not taking into account if it occurred once or multiple times. The code below, explains this better:

const str = 'in a space of time spark';
const regex = new RegExp('spa');
const globalRegex = new RegExp('spa', 'g');
console.log(regex.test(str));
//output: true
console.log(regex.lastIndex);
// doesn’t matter what position. spa is present so it outputs 0
console.log(regex.test(str));
//output: true
console.log(regex.lastIndex);
// doesn’t matter what position. spa is present so it outputs 0
console.log(regex.test(str));
//output: true
console.log(regex.lastIndex);
// doesn’t matter what position. spa is present so it outputs 0
console.log(globalRegex.test(str));
// output: true
console.log(globalRegex.lastIndex);
// output: 8
console.log(globalRegex.test(str));
// output: true
console.log(globalRegex.lastIndex);
// output: 22
console.log(globalRegex.test(str));
// output: false
console.log(globalRegex.lastIndex);
// output: 0 (because spa only occurs in position 8 and 22)

3. match()

 This method retrieves the result of matching a regular expression against a String. Instead of returning true or false, this method outputs an array of results matching our regular expression. Let’s look at an example that will match capital letters in our String. The global flag will be used to ensure that every letter of our alphabet is iterated over in our match.

const paragraph = 'TheGirl Fakesa Smile.';
const regex = /F(a)[a-z]/g;
const found = paragraph.match(regex);
console.log(found); // Should return ["Fak"]

The syntax for the match() method is match(regexp). Where regexp is our regular expression object. If you don’t put in a parameter or use the match() method directly, you’ll get an array of empty strings. If you don’t use the global flag with this method, you’ll get the same result as the exec() method. 

4. matchAll()

The matchAll() the method must be called with the global flag. The difference between this method and the match() method is the ability to return an iterator with all matched groups and capturing groups.

5. replace()

If you want to not only search and match but replace Strings, the replace() method will do the job. The provided pattern can either be a String or a RegExp.

const p = 'The girl is a beautiful girl';
console.log(p.replace('girl', 'lady'));
//output: "The lady is a beautiful girl"
 
const regex = /girl/i;
console.log(p.replace(regex, 'woman'));
// output: "The woman is a beautiful girl"

6. replaceAll()

Replace all is useful if you want to change all occurrences of a String in your text with your RegExp pattern. In the replace() method, only the first String in a text is replaced with our pattern. However, replaceAll() will substitute all occurrences of the String with our pattern, not just the first one. 

const p = 'The girl is a beautiful girl';
console.log(p.replaceAll('girl', 'lady'));
//output: "The lady is a beautiful lady"
 
const regex = /girl/g;
console.log(p.replaceAll(regex, 'woman')); //output: "The woman is a beautiful woman"

The search method search() is used to perform a search for a match between a regular expression and a String. This method doesn’t output true or false or an array of the result. Instead, it outputs a number, showing the index of the first match. For instance, the example below outputs 4 which is the index of the first capital letter “S”.

let str = "the Soup Is Sour"
let re = /[A-Z]/g
console.log(str.search(re)) //This should output 4

8. split()

We can extract substrings from our String with the split method. What this method does, is divide Strings into substrings according to our pattern. Then, it’ll return an array containing all of the substrings. We can divide Strings into words, characters, etc. with the split method.

The syntax for the split() the method is shown below:

split()
split(separator)
split(separator, limit)

With every blog we publish, our goal is to share knowledge to make confident and better coders.

For more tech blogs, please visit Knoldus Blogs. Also, please follow our LinkedIn page- FrontEnd Studio
Enjoy Coding…