Reputation: 6949
I'm working a JavaScript context detector.
It parses the UA for some common data like OS version and browser version.
It uses RegExp for pretty much everything.
Like the script to detect the Mac OS X version: /(Intel|PPC) Mac OS X (.+)[\);]/
It saves the data to an object that I'll call $
.
$.Mac
should be 10_6_7
but instead it is 10_6_7) AppleWebKit/534.24 (KHTML, like Gecko
The full ua is Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.25 Safari/534.24
It always uses the last found ; or ), when I want it to find the ; or ) immediately after the version number. How to do that?
Upvotes: 0
Views: 210
Reputation: 14619
Or, make your .+
more specific:
/(Intel|PPC) OS X ([0-9_]+)/
should do the trick, as long as you can count on your version numbers consisting only of digits and underscores.
Hope this helps!
Upvotes: 1
Reputation: 359816
Make the .+
nongreedy.
/(Intel|PPC) Mac OS X (.+?)[\);]/
Before:
var str = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.25 Safari/534.24',
re = /(Intel|PPC) Mac OS X (.+)[\);]/;
str.match(re); // ["Intel Mac OS X 10_6_7) AppleWebKit/534.24 (KHTML, like Gecko)", "Intel", "10_6_7) AppleWebKit/534.24 (KHTML, like Gecko"]
After:
var re = /(Intel|PPC) Mac OS X (.+?)[\);]/;
str.match(re): // ["Intel Mac OS X 10_6_7)", "Intel", "10_6_7"]
Upvotes: 3