-1

I need to redirect my customers to another web page, if their browser name/version will be not in a list.

I think the answer to my question is here How can you detect the version of a browser? But I don't understand it.

I think this is what I'm looking for

ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i)

looks for matches in navigator.userAgent but I don't understand the regular expression.

As a third option, I'm trying to read this, but I don't understand it either.

if(M[1]=== 'Chrome'){
        tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
        if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
}

Can anyone explain any of these simply?

Community
  • 1
  • 1
Matt D.
  • 33
  • 7

1 Answers1

0

Regular Expressions are a simple way to search text. The downside is that they're very archaic. You can learn regular expressions in a couple of weeks if you just read and practice the tutorials at http://www.regular-expressions.info/ over and over.

Everyone here was trying to write a regular expression to find the text of the browser from the user agent string, mostly because the user agent string is already pretty hard to read. You can learn about it at http://www.useragentstring.com/.

As you can see, the text of the string is all about explaining what browser is being used to access your website. So most of the regular expressions are simply attempting to find the browser name.

In your second example this is particularly evident:

opera|chrome|safari|firefox|msie|trident

In regex, the pipe is used to represent or so the above says opera or chrome or safari or firefox or msie or trident and since you might know that msie means microsoft internet explorer, you can see how that's simply a list of browsers.

What you can do just as easily is search the string for the text. In javascript this is done with indexOf but there are risks, as often user agent strings have fallback browsers listed in the event that their browser name is not understood by, for example, your if statement.

I might do something like this if I was looking for the chrome browser.

if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
    // do stuff with chrome
}

Hope that helps.

deltree
  • 3,756
  • 1
  • 30
  • 51
  • This is helpful. Thank you very much. – Matt D. Jun 11 '16 at 17:29
  • Are there any ways to find out browser's characteristics except "user.agent string"? – Matt D. Jun 11 '16 at 17:35
  • 1
    There are other ways. The truth is, a user agent string is only as trustworthy as the user. Check out how they do in here http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser – deltree Jun 11 '16 at 17:51