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';
0

2 Answers 2

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

7 Comments

Awesome! Will accept this answer. Super helpful to know I needed the extra escaping slash.
Downvoter, please let me know what is wrong.
@thefourtheye I downvoted, because I misunderstood the second sentence in your answer. Removed the downvote, but I still think the character class [\d|\.] is unusual, since it matches | characters for no real reason, so no upvote yet.
It doesn't really have anything to do with the "RegExp object" (I assume you mean constructor). It has to do with using string literal syntax, which also uses the backslash as the opening of an escape sequence.
@Paulpro You are correct :) I included that information in the answer.
|
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.]*)/);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.