Open In App

JavaScript RegExp Lookaheads

Lookaheads are the patterns that ask JavaScript to look ahead in the string to check for intended patterns in the string. Lookahead and Lookbehind are together referred to as Lookaround. Using Lookaheads we can easily capture a particular group of characters only if they appear before another set of characters. This is helpful when we want to search multiple patterns in the same string.

Syntax:



X(?=Y) //For positive lookaheads
X(?!Y) //For negative lookaheads

Types of lookaheads: There are two types of lookaheads as follows:

Note: The ‘?’ character may also be used as a quantifier.



Lookaheads are a bit confusing to understand, so let’s take some examples.

Example 1: This example demonstrates positive lookahead.




<script>
    let word1 = "butterfly";
    let word2 = "buttermilk";
    let exp = /(butter(?=fly))/;
    let result1 = (exp.test(word1));
    let result2 = (RegExp.$1);
    let result3 = (exp.test(word2))
    console.log(result1); //outputs “true”
    console.log(result2); //outputs "butter"
    console.log(result3); //outputs "false"
</script>

Explanation: In the above example, exp matches “butter” only if it is followed by “fly“.After testing the expression against word1, code outputs the contents of RegExp.$1, which is ‘butter‘ not ‘butterfly‘.The “fly” part of the pattern is contained inside of a lookahead and so isn’t returned as part of the group.

Output:

Positive Lookahead

Example 2: The previous example can be converted to negative lookahead:




<script>
    let word1 = "butterfly";
    let word2 = "buttermilk";
    let exp = /(butter(?!fly))/;
    let result1 = (exp.test(word1));
    let result2 = (exp.test(word2))
    let result3 = (RegExp.$1);
    console.log(result1); //outputs "false"
    console.log(result2); //outputs "true"
    console.log(result3); //outputs "butter"
</script>

Explanation: Here, the pattern matches “buttermilk” but not “butterfly” as “fly” doesn’t follow “butter“. After testing against word2, RegExp.$1 contains “butter” once again, not “buttermilk”.

Output:

Negative Lookahead

Let’s have a practical example to understand lookaheads properly:

Problem Statement: Write a regex to find all the items which have a present status of ‘sold’.

Sr. No. Vehicle Status
1 Bike Sold
2 Bike Unsold
3 Car Repair

The regex for the above requirement will be:

/ bike(?=\s+sold) /

In this way, we can match certain words not followed by some elements. These elements can be characters, or groups

Note: JavaScript supports regular-expression lookaheads, it does not support lookbehinds.

Supported Browsers:


Article Tags :