Sidebar

How to remove leading zeros or other character from a string.

+3 votes
2.8K views
asked Mar 11, 2014 by rich-c-2789 (16,180 points)

1 Answer

+2 votes

There are several ways to strip leading characters and some are better suited for a given situation than others.  For example, if the source data is a zero padded number you could use math or number functions.  Alernatively if the source data contains alpha characters then string funtions may be better suited.  In either case be careful that the solution you choose does what you want without side effects.  Some solutions might transform the value or strip trailing and leading characters.   For example what would you expect for the following:

var value = 000123 * 1;
qie.debug("Stripped number by * 1: " + value);produces the value 83 in javascript

Results:

Stripped number by * 1: 83

The reason we get 83.  In some javascript versions the leading zero sets the radix to 8 (octal).  This may not always be the case.  Some newer browsers default to the radix to 10 (decimal).  Note that QIE has the following warning:

"Don't use extra leading zeros '000123'."

If we start with a string it will produce the correct result.

var value = '000123' * 1;
qie.debug("Stripped number by * 1: " + value);

Results:

Stripped number by * 1: 123

Also try 

value = parseInt('000123', 10);
qie.debug("Stripped string by parseInt: " + value);

 

value = parseInt('0001A2B3C', 10);
qie.debug("Stripped string by parseInt: " + value);

 

value = StringUtils.stripStart('000123', '0');
qie.debug("Stripped string by * StringUtils.stripStart: " + value);

 

value = StringUtils.stripStart('0001A2B3C', '0');
qie.debug("Stripped string by * StringUtils.stripStart: " + value);
Results:
 
Stripped string by parseInt: 123
Stripped string by parseInt: 1
Stripped string by * StringUtils.stripStart: 123
Stripped string by * StringUtils.stripStart: 1A2B3C
 
Note the difference when alpha characters are included in the source data.  1 may not be desired but 1A2B3C may.
 
answered Mar 11, 2014 by rich-c-2789 (16,180 points)
commented Apr 17, 2014 by rich-c-2789 (16,180 points)
My preferred way to strip leading zeros in most cases will be to use the StringUtils.stripStart version above.
...