根据特定字符获取整个字符串或子字符串 [英] Get an entire string or a substring, depending on a specific character

查看:47
本文介绍了根据特定字符获取整个字符串或子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 MIME 类型的字符串,比如 application/json.现在我想将其与实际的 HTTP 标头进行比较,在本例中为 content-type.

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.

如果标头包含 MIME 类型,则很简单:

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

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

不幸的是,标题可能包含附加参数.它们总是出现在我感兴趣的值之后,并且它们之间用 ; 分隔.例如,它可以是 application/json;charset=UTF-8.

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…

我可以考虑使用

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

但这也将成功匹配值 application/jsonformatter(这是不需要的).

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

所以,长话短说:有没有比我上面描述的冗长的 if 更好的方法来比较这些值,例如使用正则表达式?

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:

  • 如果它包含分号,则返回它之前的部分.
  • 如果它不包含分号,则返回所有内容.

最有效的写法是什么?

推荐答案

我建议使用标准的解析模块,例如 media-typer,Express 在其中间件中使用该模块.

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
}

这篇关于根据特定字符获取整个字符串或子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆