Javascript Regular Expression multiple match

This question already has an answer here:

  • How can I get query string values in JavaScript? 73 answers

  • You can use a regex to do this.

    var qualityRegex = /(?:^|[&;])quality=([^&;]+)/g,
        matches,
        qualities = [];
    
    while (matches = qualityRegex.exec(window.location.search)) {
        qualities.push(decodeURIComponent(matches[1]));   
    }
    

    jsFiddle.

    The qualities will be in qualities .


    A slight variation of @alex 's answer for those who want to be able to match non-predetermined parameter names in the url.

    var getUrlValue = function(name, url) {
      var valuesRegex = new RegExp('(?:^|[&;])' + name + '=([^&;]+)', 'g'),
          matches,
          values = [];
    
      while (matches = valuesRegex.exec(url)) {
          values.push(decodeURIComponent(matches[1]));   
      }
    
      return values;
    }
    
    var url = 'http://www.somedomain.com?id=12&names=bill&names=bob&names=sally';
    
    // ["bill", "bob", "sally"]
    var results = getUrlValue('names', url);
    

    jsFiddle

    链接地址: http://www.djcxy.com/p/17606.html

    上一篇: JQuery查询字符串遍历

    下一篇: Javascript正则表达式多重匹配