Check out this script... run and see the oddity..
http://jsfiddle.net/BjJTc/
From jsfiddle
var m = 'Jan07';
var mm = 'Jan';
alert(m.replace(mm, ''));
alert(parseInt(m.replace(mm, '')));
var m = 'Jan08';
var mm = 'Jan';
alert(m.replace(mm, ''));
alert(parseInt(m.replace(mm, '')));
var m = 'Jan09';
var mm = 'Jan';
alert(m.replace(mm, ''));
alert(parseInt(m.开发者_开发问答replace(mm, '')));
var m = 'Jan10';
var mm = 'Jan';
alert(m.replace(mm, ''));
alert(parseInt(m.replace(mm, '')));
This is an Octal issue: try parseInt(val, 10)
. The leading zero makes it believe it's octal. parseInt takes a second optional parameter radix:
radix An integer that represents the radix of the above mentioned string. While this parameter is optional, always specify it to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.
So:
parseInt('09') // 0
parseInt('09', 10); // 9
You are running into a problem with the radix. Javascript is interpreting 07, 08, 09
as octal numbers. Decimal 7 and Octal 07 evaluate to the same number, while 8 & 9 do not.
Include the base 10 radix as the second param to all of your parseInt()
calls:
var m = 'Jan08';
var mm = 'Jan';
alert(m.replace(mm, ''));
alert(parseInt(m.replace(mm, ''), 10));
// ------------------------------^^^^^^
If you are trying to get the year from the string you have, you could attempt to parse it as a date then extract the number of years...
var m = 'Jan07';
var d = Date.parse('01' + m); // Parse the 1st of the month
var y=Math.floor(d/(1000*60*60*24*365.24)) + 1970; // Convert to years since 1970, then add 1970
alert(y);
Not to most elegant of solutions, but will get you the year from your MMMyy format.
Or just lose the leading letters and any leading 0-
m='Jan08';
mm=/^\D+0?/,'');
alert(m.replace(mm, ''));
精彩评论