Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this javascript function do?

Tags:

javascript

var n = {
        Android: /Android/i.test(navigator.userAgent),
        Safari: /iPhone|iPad|iPod/i.test(navigator.userAgent) && !/CriOS|Chrome|Mercury/.test(navigator.userAgent)
    };

I am curious about the /Android/i.test() function. If this a function in another file? I'm guessing it is not since the next function /iPhone|iPad|iPod/i.test() is even more curious. Is it a string compare on the 'Android' string? Could anyone provide me with some documentation?

like image 767
Roel Storms Avatar asked Dec 06 '22 19:12

Roel Storms


1 Answers

It's a method call on the regular expression /Android/i.

The /Android/i part represents a regular expression or "regex", which is used to do pattern-matching on strings.

A regular expression has a method called test, and returns true if it matches. You could rewrite that hunk above as:

androidRegex = /Android/i;
safariRegex = /iPhone|iPad|iPod/i;
criOsregex = /CriOS|Chrome|Mercury/;
var n = {
    Android: androidRegex.test(navigator.userAgent),
    Safari: safariRegex.test(navigator.userAgent) && !criOsregex.test(navigator.userAgent)
};

The syntax for declaring a regular expression in Javascript is /pattern/flags, where pattern is the pattern to compare against, and flags are additional options.

The Android one is very simple: it just compares against the string Android, with the flag i to make it case-insensitive.

The Safari one is slightly more complex, because it uses "alternation" to match iPhone, iPad, or iPod. The | character delimits alternates in a regex.

The CriOS regex, notably, leaves off the i flag because the author wants it to be case-sensitive (the default).

like image 100
N3dst4 Avatar answered Dec 29 '22 09:12

N3dst4