使用Regex / Javascript获取元素ID的组值

时间:2012-10-23 21:45:25

标签: javascript jquery regex

我有一个元素ID的DIV;例如“bgjhkn2n2-20”。我试图让正则表达式正确,所以我可以根据id动态地将报表加载到div中。

console.log(elemID)按预期打印bgjhkn2n2-20。它不打印通常前缀为元素Id的#。 console.log(repDBID[0])打印完整的元素ID;但是我无法在console.log(repDBID[0])的regextester中打印出来自类似测试的组的萤火虫。如果我在match语句中附加索引号,则返回null。

帮助?

var baseURL = window.location.protocol + "//" + window.location.hostname + "/db/";
var genREP = "?a=API_GenResultsTable&qid=";

$('#tab1 div').each(function (e){
    var elemID = this.getAttribute('id');
    console.log(elemID);
    var pattern=/([a-z0-9]{9})-([1-9]{1}[0-9]*)/g
    var repDBID = elemID.match(pattern); //get dbid    
    console.log(repDBID[0]);
    var repID = elemID.match(pattern)[2]; //get qid
    //console.log(repID);
    //$(this).load(baseURL+repDBID+genREP+repID);
     $('#repTabs').tab(); //initialize tabs
});

1 个答案:

答案 0 :(得分:0)

从你的正则表达式中删除g,它应该可以正常工作:

var baseURL = window.location.protocol + "//" + window.location.hostname + "/db/";
var genREP = "?a=API_GenResultsTable&qid=";

$('#tab1 div').each(function(e) {  // You might need `#tab1 > div`
    var parts = this.id.match(/([a-z0-9]{9})-([1-9]{1}[0-9]*)/);
    var repDBID = parts[1];
    var repID = parts[2];

    $(this).load(baseURL + repDBID + genREP + repID);

    $('#repTabs').tab();
});

这就是我的意思:

> id.match(/([a-z0-9]{9})-([1-9]{1}[0-9]*)/g);
["bgjhkn2n2-20"]
> id.match(/([a-z0-9]{9})-([1-9]{1}[0-9]*)/);
["bgjhkn2n2-20", "bgjhkn2n2", "20"]