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 >开发者_Python百科 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
someString.match(/\d+/)[0]; // 1234
Or, to specifically target digits following "comment_":
someString.match(/^comment_(\d+)/)[1]; // 1234
function ExtractId(str){
var params = str.split('_');
return params[params.length - 1];
}
var id = ExtractId('comment_1234');
var tesst = "WishID=1List"
var test = tesst.match(/WishID=(.*)List/);
alert (test[1]);
if(test[1]==""){
alert('Empty');
}
精彩评论