JavaScript / ECMAScript

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-8

Matches

  • Content-Type: text/html; charset=utf-8

Input

content-type: application/json

Matches

  • content-type: application/json

Input

Authorization: Basic xyz

No match

Same pattern, other engines

← Back to HTTP Content-Type Header overview (all engines)