2

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

3 Answers 3

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

Or, to specifically target digits following "comment_":

someString.match(/^comment_(\d+)/)[1]; // 1234
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Or just someString.split("_")[1]
0
function ExtractId(str){
    var params = str.split('_');
    return params[params.length - 1];
}

var id = ExtractId('comment_1234');

Comments

0

var tesst = "WishID=1List"
var test = tesst.match(/WishID=(.*)List/);
alert (test[1]);

if(test[1]==""){
  alert('Empty');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.