CarlGammaSagan
CarlGammaSagan

Reputation: 433

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) )) {

Upvotes: 0

Views: 167

Answers (2)

jogesh_pi
jogesh_pi

Reputation: 9782

navigator.userAgent gives you the string that hold the details of browser, OS etc. Something like this

Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36

And the regex detect if one of if them is found in the string or not. If found the condition become true else false.

Upvotes: 0

user149341
user149341

Reputation:

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.

Upvotes: 1

Related Questions