DelphiFAQ Home Search:

Javascript to trim leading 0 (zero) from text input fields

 

comments8 comments. Current rating: 4 stars (3 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));

// end hiding contents -->
</script>

Comments:

2007-04-10, 09:55:59
[hidden] from United States  
rating
would this 'trimnumber()' function affect the origional variable 's' or would it just return a new value without the zeros in front
2007-08-29, 07:50:04
anonymous from United States  
rating
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).
2007-09-10, 09:17:32
anonymous from Canada  
rating
it is really helpful
2007-09-10, 21:51:30
anonymous from United States  
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
2008-01-09, 06:15:16
anonymous from United Kingdom  
useful
2008-03-01, 13:48:54
anonymous from United States  
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.
2008-03-05, 13:53:18
anonymous from United States  
how about
function trimNumber(s) {
return s * 1;
}
2008-04-23, 07:49:36
anonymous from United States  
function trimNumber(s) {
return s * 1;
}

does not work for decimal number. 1.00 * 1 = 1

 

 

Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option.
 
It seems that you are
from Washington, US .

Info/ Feedback on this

Show city and country
Show country only
Hide my location
Leave your comment here:
Please type in the code:
photo Add a picture:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity. The owner of this web site reserves the right to delete such material.