Parse an image srcset attribute
Responsive images are configured through a single comma-separated string, and any tool that audits or rewrites them — an image CDN helper, a lint rule, a Markdown pipeline — starts by parsing it.
Implement parseSrcset(srcset) returning an array of { url, width, density } in input order. Assume no candidate URL contains a comma, so you can split the string on ,. Trim each candidate and skip empty ones, then split on whitespace: the first token is the URL and an optional second token is the descriptor.
A descriptor of digits followed by w (such as 800w) sets width to that integer and density to null. A descriptor of a number followed by x (such as 2x or 1.5x) sets density to that number and width to null. A candidate with no descriptor — or with a descriptor you do not recognise, which is ignored — gets width: null and density: 1, matching the browser's default of 1x.
An empty or missing input returns an empty array.
What it has to do
- Return an array of
{ url, width, density }objects in input order. - Split candidates on
,and separate the URL from its descriptor on whitespace. - Set
widthfrom aNwdescriptor and leavedensityasnull. - Set
densityfrom aNxdescriptor, allowing decimals, and leavewidthasnull. - Default to
width: null, density: 1when there is no recognised descriptor, and return[]for empty input.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.