Andrew Andrew - 5 months ago 26
Javascript Question

Javascript regex: How to extract an "id" from a string?

I have this string:


I want to extract the
from the string. How can I do that?

Update: I can't get any of your answers to work...Is there a problem with my code? The alert never gets called:

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?


I figured out my problem...for some reason it looks like a string but it wasn't actually a string, so now I am casting
to a string and it is working.

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

someString.match(/\d+/)[0]; // 1234

Or, to specifically target digits following "comment_":

someString.match(/^comment_(\d+)/)[1]; // 1234