A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript-regexp-sticky-property/ below:

JavaScript RegExp Sticky Property - GeeksforGeeks

JavaScript RegExp Sticky Property

Last Updated : 04 Dec, 2024

The sticky property in JavaScript regular expressions determines whether the y (sticky) flag is enabled. A sticky regular expression searches for a match starting from the current position in the target string and does not search further if a match isn't found at that exact point.

JavaScript
// Regular expression without 'y' flag
let regex1 = /test/;
console.log(regex1.sticky);

// Regular expression with 'y' flag
let regex2 = /test/y;
console.log(regex2.sticky);

Syntax

regex.sticky
Key Points Real-World Examples of the sticky Property 1. Parsing Consecutive Words JavaScript
let s = "hello hello";
let regex = /hello/y;

regex.lastIndex = 0;
console.log(regex.exec(s)); 

regex.lastIndex = 5;
console.log(regex.exec(s));

regex.lastIndex = 6;
console.log(regex.exec(s));

Output
[ 'hello', index: 0, input: 'hello hello', groups: undefined ]
null
[ 'hello', index: 6, input: 'hello hello', groups: undefined ]

The y flag ensures the regex matches only when the lastIndex points to the correct position in the string.

2. Matching Numbers in a CSV JavaScript
let csv = "123,456,789";
let regex = /\d+/y;

regex.lastIndex = 0;
while ((match = regex.exec(csv)) !== null) {
    console.log(`Matched: ${match[0]} at index ${regex.lastIndex}`);
    regex.lastIndex++;
}

Output
Matched: 123 at index 3
Matched: 456 at index 7
Matched: 789 at index 11
3. Strict Match at Current Position JavaScript
let s = "sticky test";
let regex = /sticky/y;

regex.lastIndex = 0;
console.log(regex.exec(s));

regex.lastIndex = 1;
console.log(regex.exec(s));

Output
[ 'sticky', index: 0, input: 'sticky test', groups: undefined ]
null
4. Splitting a String with Sticky Matching JavaScript
let s = "apple|banana|cherry";
let regex = /\w+/y;

let a = [];
regex.lastIndex = 0;

while ((match = regex.exec(s)) !== null) {
    a.push(match[0]);
    regex.lastIndex++;
}

console.log(a);

Output
[ 'apple', 'banana', 'cherry' ]
5. Iterative Parsing Without Backtracking

Sticky regex is ideal for scenarios where parsing must progress linearly without revisiting skipped positions:

JavaScript
let s = "key=value;key2=value2";
let regex = /\w+=\w+/y;

regex.lastIndex = 0;
while ((match = regex.exec(s)) !== null) {
    console.log(`Match: ${match[0]} at position ${regex.lastIndex}`);
    regex.lastIndex++;
}

Output
Match: key=value at position 9
Match: key2=value2 at position 21
Why Use the sticky Property?

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4