简体   繁体   中英

case-insensitive match in Javascript

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

how can I also match JPG, 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, eg 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 - gnore case 情况

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

您需要添加i旗将其标记为区分 nsensitive:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM