What does regex' flag 'y' do?

后端 未结 1 728
无人及你
无人及你 2020-12-25 11:29

MDN says:

To perform a \"sticky\" search, that matches starting at the current position in the target string, use the y flag.

相关标签:
1条回答
  • 2020-12-25 11:52

    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.

    0 讨论(0)
提交回复
热议问题