javascript 正则表达式不区分大小写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3890475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:34:37  来源:igfitidea点击:

regex case insensitivity

javascriptjqueryregex

提问by oshirowanen

How would I make the following case insensitive?

我如何使以下不区分大小写?

if ($(this).attr("href").match(/\.exe$/))
{
// do something
}

回答by Spudley

Put an iafter the closing slash of the regex.

i在正则表达式的结束斜线后面放一个。

So your code would look like this:

所以你的代码看起来像这样:

if ($(this).attr("href").match(/\.exe$/i))

回答by Sarfraz

With /imodifier:

/i修饰符:

if ($(this).attr("href").match(/\.exe$/i))
{
// do something
}

回答by user113716

Another option would be to simply manipulate the case to what you want.

另一种选择是简单地将案例操纵为您想要的。

It appears as though you are trying to match against lowercase characters.

看起来好像您正在尝试匹配小写字符。

So you could do this:

所以你可以这样做:

if ($(this).attr("href").toLowerCase().match(/\.exe$/)) {
     // do something
}

In fact, you could use .indexOf()instead of a regex if you wanted.

事实上,如果你愿意,你可以使用.indexOf()而不是正则表达式。

if ($(this).attr("href").toLowerCase().indexOf('.exe') > -1) {
     // do something
}

Of course, this would match .exein the middle of the string as well, if that's an issue.

当然.exe,如果这是一个问题,这也会在字符串的中间匹配。

Finally, you don't really need to create a jQuery object for this. The hrefproperty is accessible directly from the element represented by this.

最后,您实际上并不需要为此创建一个 jQuery 对象。该href属性可直接从 表示的元素访问this

if ( this.href.toLowerCase().match(/\.exe$/) ) {
     // do something
}

回答by Thomas

if ($(this).attr("href").match(/\.exe$/i))
{
// do something
}

回答by Dem Pilafian

Unlike the match()function, the test()function returns trueor falseand is generally preferred when simply testing if a RegExmatches. The /imodifier for case insensitivematching works with both functions.

match()函数不同,test()函数返回trueorfalse并且在简单测试RegEx 是否匹配时通常是首选。不区分大小写匹配的/i修饰符适用于这两个函数。

Example using test()with /i:

使用test()with 的示例/i

const link = $('a').first();

if (/\.exe$/i.test(link.attr('href')))
   $('output').text('The link is evil.');


evil link


邪恶链接

Fiddle with the code:
https://jsfiddle.net/71tg4dkw

摆弄代码:https:
//jsfiddle.net/71tg4dkw

Note:Be aware of evil links that hide their file extension, like: https://example.com/evil.exe?x=5

注意:注意隐藏文件扩展名的恶意链接,例如: https://example.com/evil.exe?x=5

Documentation for test():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

文档test()https:
//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test