The y flag acts differently in different methods.
It’s much more pleasant to use it now than ever.
String.prototype.search method ignores the
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);
lastIndex stays at 8.
We can only search from the beginning of the string with it.
String.prototype.match works differently depending on whether the
g flag is added with
g isn’t, it works like
g is set, then it returns an array with string parts that’s matched or
For instance, if we write:
const REGEX = /a/; REGEX.lastIndex = 7; console.log('abab'.match(REGEX).index); console.log(REGEX.lastIndex);
index is 0, and
lastIndex is 7.
It gets the first if no flag is added.
If we add the
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
The index must be exact.
lastIndex will then be updated after the match is found.
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);
[“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.
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.