JavaScript Recipes: Number Formatting

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


Trim Leading Zeros

If you have a number with a leading zero, like 010 or 02, how do you remove that zero?

There are various ways.

Using parseInt()

The most explicit is to use parseInt():

parseInt(number, 10)

10 is the radix, and should be always specified to avoid inconsistencies across different browsers, although some engines work fine without it.

Using the Unary + Operator

Another way is to use the + unary operator:

+number

Those are the simplest solutions.

Using Regular Expression

You can also go the regular expression route:

number.replace(/^0+/, '')

Check if a String Starts With Another

ES6, introduced in 2015, added the startsWith() method to the String object prototype.

This means you can call startsWith() on any string, provide a substring, and check if the result returns true or false:

'testing'.startsWith('test') //true
'going on testing'.startsWith('test') //false

This method accepts a second parameter, which lets you specify at which character you want to start checking:

'testing'.startsWith('test', 2) //false
'going on testing'.startsWith('test', 9) //true

Getting Year, Month, Day from Dates

The toISOString() method of the Date object in JS gives you the data:

new Date().toISOString()
// '2023-01-10T07:35:37.826Z'

But if you just want the year, month, day, you can slice the string:

new Date().toISOString().slice(0, 10)
// '2023-01-10'

Useful for creating date strings:

`${new Date().toISOString().slice(0, 10)}T07:00:00+02:00`

Lessons in this unit:

0: Introduction
1: Generate Random Numbers in a Range
2: Get Index in for...of Loop
3: Unlimited Function Parameters
4: Return Result from Async Function
5: Encode and Decode URLs
6: Destructuring Tips
7: ▶︎ Number Formatting
8: Regex Recipes
9: Dynamic function name in JS