问题
MDN says:
To perform a "sticky" search, that matches starting at the current position in the target string, use the y flag.
I don't quite understand it.
回答1:
Regular expression objects have a lastIndex
property, which is used in different ways depending on the g
(global) and y
(sticky) flags. The y
(sticky) flag tells the regular expression to look for a match at lastIndex
and only at lastIndex
(not earlier or later in the string).
Examples are worth 1024 words:
var str = "a0bc1";
// Indexes: 01234
var rexWithout = /\d/;
var rexWith = /\d/y;
// Without:
rexWithout.lastIndex = 2; // (This is a no-op, because the regex
// doesn't have either g or y.)
console.log(rexWithout.exec(str)); // ["0"], found at index 1, because without
// the g or y flag, the search is always from
// index 0
// With, unsuccessful:
rexWith.lastIndex = 2; // Says to *only* match at index 2.
console.log(rexWith.exec(str)); // => null, there's no match at index 2,
// only earlier (index 1) or later (index 4)
// With, successful:
rexWith.lastIndex = 1; // Says to *only* match at index 1.
console.log(rexWith.exec(str)); // => ["0"], there was a match at index 1.
// With, successful again:
rexWith.lastIndex = 4; // Says to *only* match at index 4.
console.log(rexWith.exec(str)); // => ["1"], there was a match at index 4.
.as-console-wrapper {
max-height: 100% !important;
}
Compatibility Note:
Firefox's SpiderMonkey JavaScript engine has had the y
flag for years, but it wasn't part of the specification until ES2015 (June 2015). Also, for quite a while Firefox had a bug in the handling of the y flag with regard to the ^
assertion, but it was fixed somewhere between Firefox 43 (has the bug) and Firefox 47 (doesn't). Very old versions of Firefox (say, 3.6) did have y
and didn't have the bug, so it was a regression that happened later (not defined behavior for the y
flag), and then got fixed.
回答2:
You can find an example here:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp#Example.3a_Using_a_regular_expression_with_the_.22sticky.22_flag
回答3:
You can find an example here:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp#Example.3a_Using_a_regular_expression_with_the_.22sticky.22_flag
Except that IMHO the example should be
var regex = /^(\S+) line\n?/y;
instead of
var regex = /(\S+) line\n?/y;
since with this line the code gives the same result whether you say
var regex = /(\S+) line\n?/y;
or
var regex = /(\S+) line\n?/g;
来源:https://stackoverflow.com/questions/4542304/what-does-regex-flag-y-do