2

Trying to pull the version off of the Chrome user agent which is formatted like "Chrome/34.0.1847.116".

This is working:

userAgent.match(/.*Chrome.*?([\d|\.]*)\s/i);

This is not working (and I'm trying to get it working):

var versionRegularExpression = new RegExp('.*'+'Chrome'+'.*?([\d|\.]*)\s', 'i');
userAgent.match(versionRegularExpression);

I must be formatting my new RegExp incorrectly - can anyone tell me how I am messing up?

The full user agent is:

var userAgent = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36';
Kirk Ouimet
  • 27,280
  • 43
  • 127
  • 177

2 Answers2

4

When you use RegExp object instead of RegEx literal, you need to escape the \ as well,

new RegExp('.*'+'Chrome'+'.*?([\\d|\\.]*)\\s', 'i');

Also, Chrome doesn't need to be concatenated, it can be part of the single string literal, like this

new RegExp('.*Chrome.*?([\\d|\\.]*)\\s', 'i');

As Paulpro points out in the comments section, when you use character classes, | will be taken as one of the characters allowed, not the OR operator. So, you don't need it there

new RegExp('.*Chrome.*?([\\d\\.]*)\\s', 'i');

Quoting from MDN's RegExp page,

When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:

var re = /\w+/;
var re = new RegExp("\\w+");
Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
2

There seems to be no point on matching .* before of after Chrome. You also do not need a | or to escape the . in a character class. I would use this:

userAgent.match(/Chrome\/([\d.]*)/);
Paul
  • 139,544
  • 27
  • 275
  • 264