最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Javascript regular expression not working in Firefox - Stack Overflow

programmeradmin1浏览0评论

This regular expression fails in Firefox but works in IE.

function validate(x) {
   return /.(jpeg|jpg)$/ig.test(x);
}

Can anybody explain why?

This regular expression fails in Firefox but works in IE.

function validate(x) {
   return /.(jpeg|jpg)$/ig.test(x);
}

Can anybody explain why?

Share Improve this question edited Nov 4, 2009 at 2:02 Mark Biek 151k54 gold badges159 silver badges201 bronze badges asked Nov 4, 2009 at 1:37 jamaljamal 2271 gold badge6 silver badges12 bronze badges 2
  • 2 Please update with a valid test-case (one that shows "failing" inputs). Thanks. – user166390 Commented Nov 4, 2009 at 1:39
  • can you explain how this code works? – jamal Commented Nov 4, 2009 at 1:47
Add a ment  | 

3 Answers 3

Reset to default 3

If you are testing with just the filename, then setting the 'g' flag for global doesn't make much sense since you are matching at the end of the string anyway - i ran the following:

function validate(x) {
  return /\.(jpeg|jpg)$/i.test(x);
}

var imagename = 'blah.jpg';
alert (validate(imagename));    // should be true
imagename = 'blah.jpeg';
alert (validate(imagename));    // should be true
imagename = 'blah.png';
alert (validate(imagename));    // should be false

all three tests came out as expected in FF.

As for 'how it works' - regular expressions can get quite tricky - but I will explain the details of the above pattern:

  • the slash / is used to delimit the pattern
  • the dot . has a special meaning of 'any non-whitespace character' - writing it as \. forces the patten to only match a fullstop
  • the () mean a collection (it gets more plicated, but that covers this usage)
  • the | means 'or'
  • $ means the end of the string (or the end of a line in a multi-line text)
  • the i after the second slash means 'case insensitive'
  • the g means 'global' - which doesn't make much sense in this case, so I removed it.

so..

/\.(jpeg|jpg)$/i

means "a string ending in either .jpeg or .jpg - ignoring case"

so... .JPEG, .jpg, .JpeG, etc... will all pass now...

In regex expressions, "." by itself means "any character". Did you mean "\." to mean "period"?

The function is using a regular expression pattern .(jpeg|jpg)$ to test strings. It looks like the intent is to validate filenames to make sure they have an extension of either jpg or jpeg.

As James Bailey pointed out, there is an error in that the period should be escaped with a backslash. A period in a regular expression will match any character. So, as shown, the pattern would match both imagexjpg and image.jpg.

发布评论

评论列表(0)

  1. 暂无评论