Search code examples
javascriptregexwhile-loopvendor-prefix

Get current matching regex-rule


I try to check for a given RegExp-rule in a string and need to get the current matching rule.

Here's what I've tried so far:

var prefixes = /-webkit-|-khtml-|-moz-|-ms-|-o-/g;
var match;
var str = '';

while ( !(match = prefixes.exec(str)) ) {
    str += '-webkit-';
    console.log(match); // => null
}

The match is null, but how can I get the current matching-rule (in this case -webkit-)?


Solution

  • You aren't asking for any groups in your regex, try surrounding your regex in parenthesis to define a group, e.g. /(-webkit-|-khtml-|-moz-|-ms-|-o-)/g.

    Various other issues, try:

    var prefixes = /(-webkit-|-khtml-|-moz-|-ms-|-o-)/g;
    var match;
    var str = 'prefix-ms-something';
    
    match = prefixes.exec(str);
    console.log(match);