HTTP Content-Type Header in JS
Parse the value of an HTTP Content-Type header, capturing the media type and optional charset.
Try it in the JS tester →Pattern
regexJS
Content-Type:\s*([a-z]+\/[\w.+\-]+)(?:;\s*charset=([\w\-]+))? (flags: gi)JavaScript / ECMAScript code
jsJavaScript
const re = new RegExp("Content-Type:\\s*([a-z]+\\/[\\w.+\\-]+)(?:;\\s*charset=([\\w\\-]+))?", "gi");
const input = "Content-Type: text/html; charset=utf-8";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
How the pattern works
Content-Type:\s* matches the header name and required whitespace. ([a-z]+\/[\w.+\-]+) captures the type/subtype (the i flag makes this case-insensitive). (?:;\s*charset=([\w\-]+))? optionally captures a charset parameter — UTF-8, iso-8859-1, etc.
Examples
Input
Content-Type: text/html; charset=utf-8Matches
Content-Type: text/html; charset=utf-8
Input
content-type: application/jsonMatches
content-type: application/json
Input
Authorization: Basic xyzNo match
—