HTTP Range Header Parser (JavaScript)
Parse a single-range HTTP Range header, resolve open ends against a resource size and return a satisfiable byte range.
Code
export function parseRange(header, size) {
if (!header || typeof header !== 'string') return null;
const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
if (!match) return { unsatisfiable: true };
const [, startRaw, endRaw] = match;
if (startRaw === '' && endRaw === '') return { unsatisfiable: true };
let start;
let end;
if (startRaw === '') {
const suffix = Number(endRaw);
if (suffix === 0) return { unsatisfiable: true };
start = Math.max(size - suffix, 0);
end = size - 1;
} else {
start = Number(startRaw);
end = endRaw === '' ? size - 1 : Number(endRaw);
}
if (start > end || start >= size) return { unsatisfiable: true };
return { start, end: Math.min(end, size - 1), length: Math.min(end, size - 1) - start + 1 };
}How the snippet works
HTTP Range Header Parser (JavaScript) comes down to the function parseRange.
Returns a newly built value, leaving the inputs as they were.
Points of care
- The guard
!header || typeof header !== 'string'short-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
The main signature reads export function parseRange(header, size)
Treat parseRange as the API: import it, and ignore the supporting code.
Statements that matter
return { start, end: Math.min(end, size - 1), length: Math.min(end, size - 1) - start + 1 };
if (startRaw === '' && endRaw === '') return { unsatisfiable: true };
if (start > end || start >= size) return { unsatisfiable: true };
Interactive Tools for This Topic
Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.HTTP Header AnalyzerPaste raw HTTP header lines and get a parsed name-value list with plain-language notes for common headers and security observations.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.
FAQ
- Does `parseRange` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- Does the code pull in any external packages?
- No external packages are involved; every call resolves to a built-in API. The file defines `parseRange` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.