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

And*_*rew 2 javascript regex

我有这个字符串: 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?
Run Code Online (Sandbox Code Playgroud)

解决方案:

我发现了我的问题......出于某种原因,它看起来像一个字符串,但实际上并不是一个字符串,所以现在我正在转换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
Run Code Online (Sandbox Code Playgroud)

Jam*_*mes 6

someString.match(/\d+/)[0]; // 1234
Run Code Online (Sandbox Code Playgroud)

或者,专门针对“comment_”之后的数字:

someString.match(/^comment_(\d+)/)[1]; // 1234
Run Code Online (Sandbox Code Playgroud)