Open In App

How to match multiple parts of a string using RegExp in JavaScript ?

In this article, we will try to understand how we could match multiple parts of a string using Regular Expression (RegExp) in JavaScript with the help of both theoretical explanations as well as coding examples too.

Let us first understand some below enlightened theoretical details about Regular Expressions in JavaScript and the actual object (RegExp) that will actually help us to understand our problem statement more effectively:



Regular Expressions: 

Syntax: The following syntax is the constructor notation syntax that we use in order to create a regular expression:



new RegExp(string, modifier)  

Parameters: 

Now after analyzing all the facts shown above, let us understand all the above-shown facts with help of an example (coding one) which is enlightened below:

Example 1: In this example, we will create a regular expression using the above-shown syntax and later visualize this in the output itself.




<script>
    let new_regular_expression
        = new RegExp("JavaScript", "i");
         
    console.log(new_regular_expression);
</script>

Output:

/JavaScript/i

Now let us understand our problem statement which is how to match multiple parts of a string with RegExp using the below-enlightened example

Example 2: In this example create a regular expression using the same syntax which we have seen above and later we will use a method called exec() which will help us to execute our data and calculate the desired result.




<script>
    let reg_expression =
        new RegExp("GeeksforGeeks*", "g");
 
    let data = "Organization named GeeksforGeeks"
        + " provide articles on GeeksforGeeks "
        + "platform itself";
 
    let new_container;
 
    console.log(
        `First index found at :
        ${reg_expression.exec(data).index}
        index number`
    );
 
    while ((new_container
        = reg_expression.exec(data)) !== null) {
        console.log(
            `${new_container[0]} string found lastly
            at ${new_container.index} index number`
        );
    }
</script>

Output:

First index found at : 19 index number
GeeksforGeeks string found lastly at 53 index number

Article Tags :