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
infile.ext
\.
- matches a literal dot(jpg|jpeg|png|gif)
- matchesjpg
,jpeg
,png
orgif
$
marks the end of the filename/
- matches the end of the REi
- 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
精彩评论