代码之家  ›  专栏  ›  技术社区  ›  Andrew

javascript regex:如何从字符串中提取“id”?

  •  2
  • Andrew  · 技术社区  · 15 年前

    我有这根绳子: comment_1234

    我想提取 1234 从字符串开始。我该怎么做?

    更新: 我找不到你的工作答案…我的代码有问题吗?警报从未被调用:

    var nameValue = dojo.query('#Comments .Comment:last-child > a[name]').attr('name');
    alert('name value: ' + nameValue); // comment_1234
    var commentId = nameValue.split("_")[1];
    // var commentId = nameValue.match(/\d+/)[0];
    // var commentId = nameValue.match(/^comment_(\d+)/)[1];
    alert('comment id: ' + commentId); //never gets called. Why?
    

    解决方案:

    我发现了我的问题……因为某种原因,它看起来像一根绳子,但实际上它不是一根绳子,所以现在我在铸造 nameValue 到一个字符串,它正在工作。

    var nameValue = dojo.query('#Comments .Comment:last-child > a[name]').attr('name'); //comment_1234
    var string = String(nameValue); //cast nameValue as a string
    var id = string.match(/^comment_(\d+)/)[1]; //1234
    
    3 回复  |  直到 8 年前
        1
  •  3
  •   James    15 年前
    someString.match(/\d+/)[0]; // 1234
    

    或者,特别针对“注释”后的数字:

    someString.match(/^comment_(\d+)/)[1]; // 1234
    
        2
  •  0
  •   Stefan K    15 年前
    function ExtractId(str){
        var params = str.split('_');
        return params[params.length - 1];
    }
    
    var id = ExtractId('comment_1234');
    
        3
  •  0
  •   Arun Prasad E S    8 年前

    var tesst = "WishID=1List"
    var test = tesst.match(/WishID=(.*)List/);
    alert (test[1]);
    
    if(test[1]==""){
      alert('Empty');
    }