Advertisement
Guest User

Untitled

a guest
Jun 6th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. RegExp.prototype.generator = function(string, submatch=null) {
  2.  var regexp = new RegExp(this.source, 'g')
  3.  return function *f() {
  4.   var match = null
  5.   while(match = regexp.exec(string)) {
  6.    if(submatch === null)
  7.     yield match
  8.    else if(match.length <= submatch )
  9.     throw('number of submatches does not match param submatch')
  10.    else
  11.     yield match[submatch]
  12.   }
  13.   return
  14.  }()
  15. }
  16.  
  17. RegExp.prototype.execArray = function(string, submatch) {
  18.  return [...this.generator(string, submatch)]
  19. }
  20.  
  21. String.prototype.matchArray = function(regExpAsString, submatch) {
  22.     return (new RegExp(regExpAsString)).execArray(this, submatch)
  23. }
  24.  
  25.  
  26. var foo = "'str1', 'str2', 'str3'"
  27. var r = new RegExp(/\'([^'])+\'/)
  28.  
  29. foo.matchArray(r, 1)
  30. foo.matchArray(/\'([^'])+\'/, 1)
  31. r.execArray(foo, 1)
  32.  
  33. >>> ["str1", "str2", "str3"]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement