Search code examples
javascriptstringreplacetrim

Replace leading zeros in a string with a maximum of three in Javascript


I am currently writing a method to check for the existence of 3 leading zeros in a string and if they exist to strip them from said string. I have the following logic which is pretty straightforward but I need to ensure that anything after the three digits are kept, even if the 4th character is a zero. I am getting passed strings from a message queue which add these 3 zeros on in some circumtances so the existence of a 0 in the 4th position is entirely valid and needed to be kept. What would be the best way of doing this?

const string = '0000443212334';
string.replace(/^0+/, '');

As you can see, this will remove the 4th digit too (as it is a zero) which is unwanted.


Solution

  • You can change the regex a bit,

    string.replace(/^[0]{3}/, '');