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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A single anchored regex can both validate a format and extract its parts in one pass.
- 2Distinguishing TypeError from SyntaxError gives callers precise, actionable failures.
- 3A small unit-to-multiplier lookup keeps conversion logic declarative and easy to extend.
Related explainers
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/parsing-css-durations-into-milliseconds-explained-javascript-e6b4/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.