3
votes

Having problems with RegExp in javascript. I'm trying to return just the version number and browser name ie "firefox 22.0" or "msie 8.0"

console.log(navigatorSaysWhat())

function navigatorSaysWhat()
{
  var rexp = new RegExp(/(firefox|msie|chrome|safari)\s(\d+)(\.)(\d+)/i);
  // works in ie but not in firefox
  var userA = navigator.userAgent
  var nav = userA.match(rexp);
  return nav
 }

The above expression doesn't quite work. I' m trying to match browser name and version number from the strings.

Mozilla/5.0 (Windows NT 5.1; rv:22.0) Gecko/20100101 Firefox/22.0 Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;

I've tried (firefox|msie|chrome|safari)\s(\d+)(./\/)(\d+) to match the backslash or (firefox|msie|chrome|safari)\s(\d+)(*)(\d+) for any character, but no dice.

1
Your title does not really reflect your problem. And on what language is it (since Regex-es differ a lot)? - Richard

1 Answers

6
votes

Regular expressions are case-sensitive. Ignore case by adding (?i) or other means provided by the regular expression engine you are using.

(?i)(firefox|msie|chrome|safari)[/\s]([\d.]+)

Here's Python example.

>>> agents = 'Mozilla/5.0 (Windows NT 5.1; rv:22.0) Gecko/20100101 Firefox/22.0 Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 1.1.4322; .NET4.0C'
>>> [[m.group(1), m.group(2)] for m in re.finditer(r'(?i)(firefox|msie|chrome|safari)[\/\s]([\d.]+)', agents)]
[['Firefox', '22.0'], ['MSIE', '8.0']]

In Javascript:

var agents = 'Mozilla/5.0 (Windows NT 5.1; rv:22.0) Gecko/20100101 Firefox/22.0 Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 1.1.4322; .NET4.0C';
agents.match(/(firefox|msie|chrome|safari)[/\s]([\d.]+)/ig)
=> ["Firefox/22.0", "MSIE 8.0"]