# Remove leading zeros from a string in JavaScript

Oct 12, 2023#javascript#how-to

Handling a numeric value as a string with leading zeros is typically necessary in specific scenarios where the leading zeros have significance or are part of the desired formatting. Here are a few common situations:

• Padding numbers to a consistent length
• ZIP codes and phone numbers
• In date and time representations
• Preserving the user input as-is

Itâ€™s important to handle numeric values as strings with leading zeros to ensure that the data retains its intended format and accuracy. When the leading zeros have a specific meaning or are part of a data format, converting them to numbers can lead to data loss or misinterpretation.

The need to remove leading zeros from a string often arises for various practical reasons:

• Leading zeros are usually irrelevant in mathematical operations.
• Leading zeros can affect database storage efficiency.
• Leading zeros may not be desirable when displaying data to users.
• Leading zeros can affect sorting and searching algorithms.

There are different methods to remove leading zeros from a string depending on whether the string is a general string or a numeric string. A general string is any string that may contain any characters, while a numeric string is a string that represents a number in some format. Here is a summary of some of the methods for both types of strings:

• For general strings, use replace() method with a regular expression.
• For numeric strings, convert the string to a number to remove any leading zeros.
• Another option is to use Lodashâ€™s _.trimStart() function.
• You can always write a custom function to remove leading zeros from any string.

## Converting string to number

In JavaScript, a Number data type does not contain leading zeros. When you convert a string to a number, leading zeros are automatically removed during the conversion process. You can use the resulting value as either a number or a string depending on your specific requirements.

You can use parseInt function, Number constructor, the unary plus operator, or mathematical functions to remove leading zeros from a valid numeric value in string.

const str = "000123";

// Using parseInt() function
const num1 = parseInt(str, 10);
console.log(num1); // 123

// Using Number constructor
const num2 = Number(str);
console.log(num2); // 123

// Using the unary plus operator
const num3 = +str;
console.log(num3); // 123

// Using mathematical functions (such as subtraction)
const num4 = str - 0;
console.log(num4); // 123

In all cases, JavaScript recognizes the string as a numeric representation and converts it to a number, removing any leading zeros as part of that process. Itâ€™s a deliberate conversion from a numeric string to a number, and the removal of leading zeros is a natural consequence of that conversion.

However, these methods may have different behaviors for strings that contain hex, octal, binary literals, and a few more edge cases, which will result in NaN:

- Non numeric characters
- Empty string
- Exponential notation
- Infinity and -Infinity
- Hexadecimal, octal, and binary notation
- The decimal point character (either "." or ",")
- Overflow or loss of precision

Converting a string to number is a straightforward and easy-to-understand method. It is a relatively efficient way to remove leading zeros, especially when working with large datasets, as JavaScriptâ€™s built-in conversion functions are optimized.

## Using regular expressions

One way to use regular expressions to remove leading zeros from a string in JavaScript is to use the replace() method with a pattern that matches one or more zeros at the beginning of the string.

// A string with leading zeros
let str = "000123";

// Use replace() with a regular expression to remove leading zeros
let newStr = str.replace(/^0+/, "");

// Print the result
console.log(newStr); // "123"

The regular expression /^0+/ matches one or more zeros at the start of the string and replaces them with an empty string.

• / and / are the delimiters that mark the start and end of the pattern.
• ^ is an anchor that matches the start of the string.
• 0 is a literal character that matches the digit zero.
• + is a quantifier that matches one or more occurrences of the preceding character.

## Using a custom function

You can create a custom function to remove leading zeros by iterating through the string and removing zeros until a non-zero character is encountered.

function removeLeadingZeros(input) {
let result = input;
while (result[0] === '0') {
result = result.substring(1);
}
return result;
}

const str = "00123";
console.log(newStr); // "123"

The function is straightforward and easy to understand. It uses a simple while loop to remove leading zeros from the input string. It can be used for various strings, not just integers.

The function allows you to have fine-grained control over how leading zeros are removed or modified. If you need to implement additional logic, it can be easily integrated into the function.

## Using trimStart of Lodash

Lodash is a popular JavaScript library that provides many useful utility functions for working with arrays, objects, strings, and more.

One of the functions that Lodash provides is _.trimStart(), which removes leading whitespace or specified characters from a string. You need to pass the string as the first parameter and the character zero "0" as the second parameter. For example:

const _ = require("lodash");

let str = "000123";
let newStr = _.trimStart(str, "0");
console.log(newStr); // "123"

This will return a new string with only the valid decimal digits remaining. However, this may not be what you want if you want to preserve the hexadecimal literal as a whole. Therefore, it is important to choose the method that suits your use case.