3

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
  • 1
    Your title does not really reflect your problem. And on what language is it (since Regex-es differ a lot)? Commented Jul 23, 2013 at 8:50

1 Answer 1

5

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"]
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, I naïvely assumed that reg expressions were universal and therefore failed to mentioned that I was working in JavaScript.
@GhoulFool, Added a Javascript version. Check it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.