nzakas / understandinges6

Content for the ebook "Understanding ECMAScript 6"

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

The Regular Expression y Flag

wangjing013 opened this issue · comments

  1. The lastIndex property is only honored when calling methods that exist on the regular expression object, like the exec() and test() methods. Passing the regular expression to a string method, such as match(), will not result in the sticky behavior

The result is that the match() method is also affected by sticky

  let text = "hello1 hello2 hello3";
  let stickyPattern = /hello\d\s?/y;
  console.log(text.match(stickyPattern));   // ['hello1 ',index: 0,input: 'hello1 hello2 hello3',groups:undefined]
  console.log(stickyPattern.lastIndex);       // 7
  console.log(text.match(stickyPattern));  // [
  'hello2 ', index: 7,input: 'hello1 hello2 hello3',groups: undefined]
  console.log(stickyPattern.lastIndex);      // 14

or

  let text = "ello1 hello2 hello3";
  let stickyPattern = /hello\d\s?/y;
  console.log(text.match(stickyPattern));   // null
  console.log(stickyPattern.lastIndex);       // 0

firefox 75.0 64bit windows 7 - my console results

let text = "hello1 hello2 hello3";
undefined
let stickyPattern = /hello\d\s?/y;
undefined
console.log(text.match(stickyPattern));
undefined
Array [ "hello2 " ]
debugger eval code:1:9
console.log(stickyPattern.lastIndex);
undefined
14 debugger eval code:1:9
console.log(text.match(stickyPattern));
undefined
null debugger eval code:1:9
console.log(stickyPattern.lastIndex);
undefined

Sorry, this doesn't appear to contain anything actionable, so closing.