Andrew Andrew - 17 days ago 5
Javascript Question

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

I have this string:

comment_1234


I want to extract the
1234
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?


Solution:



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
nameValue
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

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

Or, to specifically target digits following "comment_":

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