Search code examples
javascriptjquerybrowser-detection

syntax explanation for javascript browser detection with navigator.userAgent


What is the below syntax doing? More specifically, what exactly is the / and the i.test(navigator.userAgent)? Is this jquery stuff? Thanks!

    if(( /(ipad|iphone|ipod|android|windows phone)/i.test(navigator.userAgent) )) {

Solution

  • This:

    /(ipad|iphone|ipod|android|windows phone)/i
    

    is a regular expression literal. In this case, it's a expression that will match any of the substrings ipad, iphone, ipod, android, or windows phone. The i modifier at the end makes it case-insensitive.

    This:

    .test(navigator.userAgent)
    

    is calling the test() method on that object. So it's checking whether navigator.userAgent contains any of the strings mentioned above.