开发者

regex case insensitivity

How would I make the following case insensitive开发者_Go百科?

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


Put an i after the closing slash of the regex.

So your code would look like this:

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


With /i modifier:

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


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.

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

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

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

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


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


Unlike the match() function, the test() function returns true or false and is generally preferred when simply testing if a RegEx matches. The /i modifier for case insensitive matching works with both functions.

Example using test() with /i:

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

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


regex case insensitivity

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

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜