Explain Codes LogoExplain Codes Logo

Delete first character of a string if it's '0'

javascript
string-manipulation
regular-expressions
functions
Nikita BarsukovbyNikita Barsukov·Sep 30, 2024
TLDR

Triumphantly trim a leading '0' from a given string using the power of a ternary operator combined with the slice() method:

let str = "054321"; str = str.startsWith('0') ? str.slice(1) : str;

Seeking efficiency? Have multiple leading zeros? Fear not, our trusty regular expressions come to the rescue:

let paddedNumber = "0001234"; paddedNumber = paddedNumber.replace(/^0+/, ""); // Kick out those zeros!

Unleashes an empty string on all the unsuspecting leading zeros, erasing them from existence.

Unveiling the wizards of string manipulation

Regular expressions - the zero exterminator

If your string is plagued by an army of multiple leading zeros, our heroic regular expression can defeat them all:

let numberString = "000102030"; numberString = numberString.replace(/^0+/, ""); // Zeros? Not on my watch!

Coding the charAt() loop - looping to save the day

In uncertain terrains of strings, looping with charAt() checks each character and removes all leading zeros, no matter their count:

let uncertainString = "000abc"; while (uncertainString.charAt(0) === '0') { uncertainString = uncertainString.substring(1); // One zero bites the dust! }

Slice vs. substring - a friendly duel

In the realm of JavaScript, slice() is often hailed over substring() for its readability and intuitive use:

let slicedString = "0123"; slicedString = slicedString.slice(1); // "123", no need for (1, length)

Beyond the basics - advanced usage and caution

Handling the unpredictable - non-string input

In JavaScript's dynamic terrain, a friendly typeof check guards against non-string input:

let input = 123; input = typeof input === 'string' ? input.replace(/^0+/, '') : input.toString().replace(/^0+/, ''); // Gotta be string to sing!

Lonely zeros and empty strings

Empty strings or strings housing lonely zeros need a special touch for avoiding unpredictable occurrences:

let peculiarString = "0"; peculiarString = peculiarString.replace(/^0+$/, "0"); // All alone? We'll take you home.

Cleanliness with functions

Building a function can enhance code readability, modularity and your programming karma:

function trimLeadingZeros(str) { return str.replace(/^0+/, ''); } let myString = "00456"; myString = trimLeadingZeros(myString); // "456", zero-free and flying high!

String immutability - the unchangeable fact

In JavaScript, strings are immutable. Every operation creates a new string. Beware, string operations can chew through performance when used recklessly in high-load scenarios. Use wisely, coder!