tshad said:
I have the following:
if (((strYr.charAt(0)<="0") || (strYr.charAt(0)>="9")) && strYr.length>1)
strYr=strYr.substring(1);
I am trying to take any blanks out of the year.
I guess you are getting user-entered text from a text input and
attempting to format it into a 2 digit year. If that is correct, then
as Mick White indicated the above is inadequate.
but if "strYr = 05", it takes out the 0??????
This expression will result in the variable 'strYr' being given the
numeric value '5' and strYr will be a type number. If printed, it will
appear as '5', not '05'.
var y = 05;
alert( y + ' is a ' + typeof y ) // displays '5 is a number'
However, if you give strYr the string '05', then strYr will be a type
string and will print as '05':
var y = '05';
alert( y + ' is a ' + typeof y ) // displays '05 is a string'
Is there something wrong with this statement?
Depends on your point of view. If strYr is a value retrieved from a
text input it will be a string. If your intention is to ensure that
it is a 2 digit number, then firstly:
strYr = strYr.replace('\D'g,'');
will remove all non-digit characters. Subsequently you should test
that the resulting strYr falls within a range that you consider valid.
And note that two-digit years may still be subject to year 2000 issues.
There are some helpful hints on date validation and formatting here:
<URL:
http://www.merlyn.demon.co.uk/js-dates.htm>
Having tested that you are happy with whatever was entered, you may
want to format strYr as a 2 digit string for output.
Formatting is usually left until the very end, typically there isn't
much point in bothering about it beforehand. Provided that you ensure
that strYr is at least one digit (0-9), then the following function, if
given a non-negative integer, will return a two digit string:
function towDigit(x){
return '' + ( (x<10)? '0'+ +x : x.match(/\d\d$/) );
}
Numbers from 0 to 9 will have a '0' prepended, numbers greater than 99
will have just the the last two digits returned.
'+x' converts x to a number, removing any existing leading zero.
Prepending a string zero '0' or empty string '' ensures the result is a
string.
Here is a brief implementation:
Enter a year (0 to 99):
<input type="text" onblur="
var y = checkYr(this.value);
alert( ((y)? 'Year is ' + y : 'Year must be 0 to 99') );
">
<script type="text/javascript">
function checkYr(y){
y = y.replace(/\D/g,'');
if ( '' == y ) {
return false;
} else {
// Test for y within suitable range here
// return false if it fails.
}
return towDigit(y);
}
function towDigit(x){
return '' + ( (x<10)? '0'+ +x : x.match(/\d\d$/) );
}
</script>