Is there any way to retrieve a appended int value to a String in javaScript?
I am cur开发者_如何学Gorently working on a project that dynamically displays DB content into table. To edit the table contents i am want to use the dynamically created "string"+id value.
Is there any way to retrieve the appended int value from the whole string in javaScript?
Any suggestions would be appreciative...
Thanks!!!
If you know that the string part is only going to consist of letters or non-numeric characters, you could use a regular expression:
var str = "something123"
var id = str.replace(/^[^\d]+/i, "");
If it can consist of numbers as well, then things get complicated unless you can ensure that string
always ends with a non-numeric character. In which case, you can do something like this:
var str = "something123"
var id = str.match(/\d+$/) ? str.match(/\d+$/)[0] : "";
(''+string.match(/\d+/) || '')
Explanation: match all digits in the variable string
, and make a string from it (''+
).
If there is no match, it would return null, but thanks to || ''
, it will always be a string.
You might try using the regex:
/\d+$/
to retrieve the appended number
精彩评论