javascript 23 lines · 6 steps

Parsing CSS durations into milliseconds

A small parser that validates a CSS time string with a regex and converts it to a millisecond number.

Explained by highlit
1const UNIT_MULTIPLIERS = {
2 ms: 1,
3 s: 1000,
4};
5 
6export function parseCssDuration(input) {
7 if (typeof input !== 'string') {
8 throw new TypeError(`Expected a string, received ${typeof input}`);
9 }
10 
11 const trimmed = input.trim();
12 const match = /^(-?(?:\d+\.?\d*|\.\d+))(ms|s)$/i.exec(trimmed);
13 
14 if (!match) {
15 throw new SyntaxError(`Invalid CSS duration: "${input}"`);
16 }
17 
18 const [, rawValue, rawUnit] = match;
19 const value = Number.parseFloat(rawValue);
20 const unit = rawUnit.toLowerCase();
21 
22 return value * UNIT_MULTIPLIERS[unit];
23}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A single anchored regex can both validate a format and extract its parts in one pass.
  2. 2Distinguishing TypeError from SyntaxError gives callers precise, actionable failures.
  3. 3A small unit-to-multiplier lookup keeps conversion logic declarative and easy to extend.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Parsing CSS durations into milliseconds — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code