2

This particular application is returning content-type headers in the format application/json;charset=UTF-8

I'm not sure if this could change and get reduced to 'application/json' only or may be if I reuse this code somewhere else for?

My code is

response.headers['Content-Type'].match(/text\/application//json/i)

How to best check for content type application/json???

user2727195
  • 5,822
  • 10
  • 60
  • 102

3 Answers3

2

You can use RegExp /application\/json/

var response = {"Content-Type":"application/json;charset=UTF-8"};
console.log(response["Content-Type"].match(/application\/json/)[0]);
guest271314
  • 1
  • 10
  • 82
  • 156
1

I think you are doing right, You can check this using regex . If it returns null then it means it is not json.

if (response.headers['Content-Type'].match(/application\/json/i)){

   // do your stuff here
}

Other way is to find application/json string in header string

if (response.headers['Content-Type'].contains('application/json')){

   // do your stuff here
}
Zohaib Ijaz
  • 17,180
  • 5
  • 28
  • 50
0

There are multiple JSON content-types. Not all of them are "official", but if you are trying to match them all, try this regex:

^((application\/json)|(application\/x-javascript)|(text\/javascript)|(text\/x-javascript)|(text\/x-json))(;+.*)*$

You can add / delete content types from the regex, just remember to put proper parenthesis around them.

Community
  • 1
  • 1
Jezor
  • 2,330
  • 1
  • 15
  • 38
  • A better refactoring would be `^(application\/(json|x-javascript)|text\/(x-)?javascript|x-json)(;.*)?$`. The slashes don't need to be escaped for the regex to be correct, but if your language uses slashes as regex separators, you do need the backslashes for that reason. – tripleee Jun 30 '16 at 07:56