The y flag acts differently in different methods.
Since 2015, JavaScript has improved immensely.
It’s much more pleasant to use it now than ever.
In this article, we’ll look at new JavaScript regex features.
The String.prototype.search
method ignores the y
flag.
lastIndex
isn’t changed by it.
For example, if we have:
const REGEX = /foo/y;
REGEX.lastIndex = 8;
const match = 'barfoobarfoo'.search(REGEX);
console.log(match.index);
console.log(REGEX.lastIndex);
Then match
us undefined
and lastIndex
stays at 8.
We can only search from the beginning of the string with it.
The String.prototype.match
works differently depending on whether the g
flag is added with y
.
If g
isn’t, it works like exec
.
If g
is set, then it returns an array with string parts that’s matched or null
.
For instance, if we write:
const REGEX = /a/;
REGEX.lastIndex = 7;
console.log('abab'.match(REGEX).index);
console.log(REGEX.lastIndex);
Then index
is 0, and lastIndex
is 7.
It gets the first if no flag is added.
If we add the y
flag:
const REGEX = /a/y;
REGEX.lastIndex = 2;
console.log('abab'.match(REGEX).index);
console.log(REGEX.lastIndex);
Then the match is only returned if the search starts from the lastIndex
.
The index must be exact.
lastIndex
will then be updated after the match is found.
If the g
flag is set, then match
will match all the substrings and put them in the array.
For example, we can write:
const REGEX = /a|b/g;
REGEX.lastIndex = 0;
console.log('abab'.match(REGEX));
console.log(REGEX.lastIndex);
And match
returns [“a”, “b”, “a”, “b”]
.
lastIndex
is still 0.
lastIndex
is ignored with the g
flag enabled.
The result is the same with the gy
flags added.
match
and lastIndex
all give us the same result.
Vinew Technologies is the leading Custom web development services company known for creating state of the art custom business websites that help you engage your audience better.
With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...
You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...
We are the best offshore web development company in India providing web applications on Blockchain, AI & Chatbots. 15+ Yrs Exp., Save upto 60% on development.
Get Best out from Web Design and Development Services from Vinew Technologies,We have a dedicated team of experienced and knowledgeable web developers, designers and testers. Therefore, we have proficiency in analyzing, developing and designing the necessity of intricate Website Development projects.