How can I remove leading zeros?

TEdwards
Kilo Sage

Hello all,

I have a requirement to remove the leading zeros from a string variable on a catalog item. The variable ('kronos_id_1') is populated using the onChange client script that follows. The employee_number may have up to five zeros preceding the number. Is there any way to remove them? It would not necessarily need to be onChange, as long as the result is that the zeros no longer appear after submission.

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    var name = g_form.getValue('name_1');
    if (name != '') {
        var gr = new GlideRecord('sys_user');
        gr.addQuery('sys_id', name);
        gr.query(function(gr) {
            if (gr.next()) {
                g_form.clearValue('kronos_id_1');
                g_form.clearValue('email_address_1');

                g_form.setValue('kronos_id_1', gr.employee_number);
                g_form.setValue('email_address_1', gr.email);

                g_form.setReadOnly('kronos_id_1', 'true');
                g_form.setReadOnly('email_address_1', 'true');
            }
        });
    } else {
        g_form.clearValue('kronos_id_1');
        g_form.clearValue('email_address_1');
    }
}

Thank you in advance for any assistance you can provide.

1 ACCEPTED SOLUTION

If you use parseInt() it will drop the leading zeroes as well. Converting it to an integer will just remove them which is all +num is doing.

View solution in original post

8 REPLIES 8

Community Alums
Not applicable

Try to add plus infront - if your variable is x = "0001" try with  y =  +x   - this will cast it to number and loose the leading zeroes

 

find_real_file.png

Unrelated, but I was trying to remove leading zeros from a date in Flow Designer and using the Add math variable transformation worked for me.

Date input data pill > Date to String transform (dd custom format) > String to Number transform > Add (zero): converted '02' to '2'

Wouldn't have been able to do so without this comment---thanks!

Kieran Anson
Kilo Patron

Hi,

you can use the regex replace method for this, see below. FYI GlideRecord isn't supported / recommended in client scripts.

var num = "000012455";
var a = num.replace(/^0+/, '');
a;

Community Alums
Not applicable

better is

var a = +num; 

🙂