开发者

case-insensitive match in Javascript

开发者 https://www.devze.com 2023-03-14 10:05 出处:网络
I have this expression: match(\'(\\.jpg|\\.jpeg|\\.png|\\.gif)$\') how can I also match JPG,开发者_如何学JAVA Jpg, jPG etc. ?The next RE considers names like file.GIF and file.gif as images, but not

I have this expression: match('(\.jpg|\.jpeg|\.png|\.gif)$')

how can I also match JPG,开发者_如何学JAVA Jpg, jPG etc. ?


The next RE considers names like file.GIF and file.gif as images, but not .gif or file.htm:

var file = "image.png";
if (/.+\.(jpg|jpeg|png|gif)$/i.test(file)) {
    alert("The file is an image")
}

/.+\.(jpg|jpeg|png|gif)$/i is a regular expression and regex.test(string) returns true if string was matched and false otherwise.

  • / - begin of RE
  • .+ - matches one of more characters, e.g. file in file.ext
  • \. - matches a literal dot
  • (jpg|jpeg|png|gif) - matches jpg, jpeg, png or gif
  • $ marks the end of the filename
  • / - matches the end of the RE
  • i - ignore case

See also http://www.regular-expressions.info/javascript.html


You need to add the i flag to mark it as case-insensitive:

match(/.../i)


You need to specify i modifier

/i makes the regex match case insensitive.

So given any string ending with those extensions it will match regardless of the letter case.

Given the following string: ".jPg"

/\.(jpe?g|gif|png)$/i       // matches
/\.(jpe?g|gif|png)$/        // doesn't match
/.+\.(jpe?g|gif|png)$/i     // doesn't match (requires filename)

See an example on gskinner

0

精彩评论

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