Golo Roden
Golo Roden

Reputation: 150664

Get an entire string or a substring, depending on a specific character

I have a string that contains a MIME type, say application/json. Now I want to compare this against an actual HTTP header, in this case content-type.

If the header contains the MIME type, then it's as easy as:

if (mimeType === contentType) { ... }

Unfortunately, the header may contain additional parameters. They always come after the value I'm interested in, and they are separated from it by a ;. E.g., it could be application/json; charset=UTF-8.

So now basically I need to run:

if (mimeType === contentType.substring(0, contentType.indexOf(';'))) { ... }

The problem is that the first case still can happen, so now we have:

if (mimeType === contentType ||
    mimeType === contentType.substring(0, contentType.indexOf(';'))) { ... }

Things start to get lengthy…

I could think of comparing them using

if (mimeType === contentType.substring(0, mimeType.length)) { ...}

but this would also successfully match the value application/jsonformatter (which is not desired).

So, to cut a long story short: Is there a better way to compare these values than my lengthy if described above, e.g. using a regular expression?

Basically I'm thinking of an expression that shortens the header if necessary according to the following rules:

What is the most effective way of writing this?

Upvotes: 2

Views: 220

Answers (2)

loganfsmyth
loganfsmyth

Reputation: 161467

I'd recommend using a standard parsing module like media-typer, which Express uses in its middleware.

var typer = require('media-typer');

var obj = typer.parse(contentType);
if (obj.type === 'application' && obj.subtype === 'json'){
    // Success
}

Upvotes: 1

anubhava
anubhava

Reputation: 785226

You can use a regex match:

if ( mimeType.match(/^application\/json(?= *;|$)/i) ) {
    // matched
}

RegEx Demo

Here (?= *;|$) is positive lookahead that will make sure that searched string application/json is either followed by optional spaces and ; OR else it is the only string in the input.

Upvotes: 2

Related Questions