nzakas / understandinges6

Content for the ebook "Understanding ECMAScript 6"
5.45k stars 796 forks source link

The Regular Expression y Flag #446

Closed wangjing013 closed 3 years ago

wangjing013 commented 4 years ago
  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
joekingTheThird3 commented 4 years ago

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

nzakas commented 3 years ago

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