I am passing the name of a variable into a javascript function onmouseover event. The variable being passed in starts with letters and ends with numbers, and I want to extract the numbers from the variable name. How can I do that?
Example code:
Lets say we pass in x = abc123
function(x){
extractednumber = parseInt(x.substring(2))
document.write(extractednumber);
}
EDIT: The variable name has 3 characters in fro开发者_开发问答nt and a unknown number of digits behind.
a simple regexp pattern :
x.match(/([0-9]*)$/)[0]
then you could write :
function(x){
extractednumber = parseInt(x.match(/([0-9]*)$/)[0]);
document.write(extractednumber);
}
function GetNumber(num)
{
var numberPart = num.replace (/[^\d]/g, “”); //use only digits
var extractednumber = parseInt(numberPart, 10);
return extractednumber;
}
Use regular expressions to parse the string:
if (/(\d+)$/.test(x))
extractedNumber = parseInt(RegExp.$1, 10);
If you always have exactly three characters in front, and then an unknown number of digits afterward, you can just use substr.
function(inputString) {
return inputString.substr(3, inputString.length);
}
精彩评论