JavaScript Document (8) Events (8) ExtJS (9) Strings (3)
Exchange Links About this site Links to us 
|
Javascript to trim leading 0 (zero) from text input fields
10 comments. Current rating: (4 votes). Leave comments and/ or rate it.
Question: I need to trim leading 0 (zero) from text input fields
Answer: Use the Javascript substr() function, or just copy trimNumber() from below.
 | |  | | <script language="JavaScript" type="text/javascript">
<!--
function trimNumber(s) {
while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
return s;
}
var s = '00123';
alert(s + '=' + trimNumber(s));
</script>
| |  | |  |
Comments:
|
|
|
|
would this 'trimnumber()' function affect the origional variable 's' or would it just return a new value without the zeros in front
|
|
|
|
|
A pretty nice script, elegant... One little modification... the javascript 'substr' has an overload that allows one parameter (the start position). If you don't specify the number of characters it will read to the end of the string (even if the string is 10,001 characters long, which yours wont do).
|
|
|
|
|
it is really helpful
|
|
|
|
|
SERIOUS QUESTION THAT WOULD PREFER ANSWERING
would this 'trimnumber()' function affect the original variable 's' or would it just return a new value without the zeros in front
|
|
|
|
|
useful
|
|
|
|
|
How about using Regular Expressions instead:
function trimNumber(s) {
return s.replace(/^0+/, '');
}
Same result with no looping. The original value of s is not affected by either function.
|
|
|
|
|
how about
function trimNumber(s) {
return s * 1;
}
|
|
|
|
|
function trimNumber(s) {
return s * 1;
}
does not work for decimal number. 1.00 * 1 = 1
|
|
|
|
|
Hi there,
I need to do the opposite, I have a 3 char field in which I only want the user to input numbers and if he only inputs a 1 or 2 digits, add the leading 0, any suggestions?
Thanks in advance
Ed.
|
|
|
|
|
I found simply multiplying the number by one worked, e.g. when you've got '08' and you want just '8':
var myHour = '08';
myHourNoZeros = myHour*1;
don't know if this works everywhere...
|
|