Skip to content

Instantly share code, notes, and snippets.

@bpholt
Last active December 18, 2015 17:19
Show Gist options
  • Select an option

  • Save bpholt/5817999 to your computer and use it in GitHub Desktop.

Select an option

Save bpholt/5817999 to your computer and use it in GitHub Desktop.
JavaScript regular expression to find headers in an HTTP response
TestCase('regex to find HTTP headers', {
headerFinderRegex: /^([-!#-'*+.0-9A-Z^-z|~]+:)/gm,
'test only valid headers are highlighted': function () {
var addValue = function(s) { return s + ' value\n';},
addColon = function(s) { return s + ':';},
wrapWithStrong = function(s) { return "<strong>" + s + "</strong>";},
invalidCharacters = (function() {
var invalidCharacters = ["(", ")", "<", ">", "@", ",", ";", ":", "\\", '"', "/", "[", "]", "?", "=", "{", "}", ' ', '\t'];
for (var i = 0; i < 32; i++) {
invalidCharacters.push(String.fromCharCode(i));
}
invalidCharacters.push(String.fromCharCode(127));
return invalidCharacters;
}()),
invalidHeaders = invalidCharacters.map(addColon).map(addValue).join(''),
validHeadersNames = ['Accept', '42!What', 'x-header'].map(addColon);
assertEquals(invalidHeaders, invalidHeaders.replace(this.headerFinderRegex, "<strong>$1</strong>"));
assertEquals(validHeadersNames.map(wrapWithStrong).map(addValue).join(''), validHeadersNames.map(addValue).join('').replace(this.headerFinderRegex, "<strong>$1</strong>"));
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment