Skip to content

Proof of concept: simulating sticky mode in pre-ES6 environemnts... #152

@pygy

Description

@pygy

It is possible, with some hand holding, to simulate sticky matching with normal RegExps.

function stickify(original) {
  var matcher = new RegExp(original.source+'|()', 'g'+original.flags) //imagine we are deduping `g`s here
  return {
    exec: function(str) {
      matcher.lastIndex = this.lastIndex;
      var res = matcher.exec(str)
      if (res && res.pop() == null) return res // setting `this.lastIndex`  elided for the demo
      else return null
    },
    lastIndex: 0
  }
}

By appending |() to the source, you ensure that the match will succeed no matter what at the given index. If original doesn't match, the last capture will be '', null otherwise.

The trouble now is to convince UAs to treat the resulting object as a RegExp in String.prototype.* context... I suppose that in ES6 you could extend native RegExps, but the polyfill is not needed there since ES6 introduces the y flag...

Edit: now the code actualy works :)

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions