views:

48

answers:

3

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
+2  A: 
someString.match(/\d+/)[0]; // 1234

Or, to specifically target digits following "comment_":

someString.match(/^comment_(\d+)/)[1]; // 1234
J-P
I am not able to get this to work. I think there must be an error in the code which prevents it from completing the function because my alert never gets called.
Andrew
Or just `someString.split("_")[1]`
darkporter
Andrew, please show us how you're using the code I provided.
J-P
I added an update showing the code I am using
Andrew
A: 

well,, if you don't like using regex,, there is a hack for this one..

you can use the string split function to split it into an array, then the id is in the last part of the array.

it's just a simple stupid way to do it, however, regex is better for sure

Maxim Mai
A: 
function ExtractId(str){
    var params = str.split('_');
    return params[params.length - 1];
}

var id = ExtractId('comment_1234');
Stefan K