AniUI Academy
medium+250 XPPractice

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 width from a Nw descriptor and leave density as null.
  • Set density from a Nx descriptor, allowing decimals, and leave width as null.
  • Default to width: null, density: 1 when there is no recognised descriptor, and return [] for empty input.

Your workspace

Try it yourself
Loading playground...

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.