Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
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 a Regular Expression
You can also use a regular expression:
number.replace(/^0+/, '')
Check if a String Starts With Another
ES2015, 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 whether the result is 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 JavaScript gives you the date:
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`