Question

I know that IE11 changed the way navigator.userAgent is sent, and I've seen this response. This works well if all we need is IE11 and above, but we need IE9 and above. I had read somewhere that the Trident code name was introduced in IE9, but a quick test of IE8 shows that the user agent there also contains Trident.

My regex is not very good; how can I split out these strings to determine what's between Trident/ and the following semicolon so I can tell which version I'm dealing with? (Please don't tell me to use feature detection instead; that's not an option here.)

IE 8:

"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; BO1IE8_v1;ENUS)"

IE 9:

"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)" 

My existing code (which doesn't catch IE8) looks like this:

if (navigator.userAgent.match(/Trident/)) {
   // it's supported; do stuff
}

Basically, I'm trying to get the 5.0 from IE9 and the 4.0 from IE8.

Was it helpful?

Solution

My regex is not very good; how can I split out these strings to determine what's between Trident/ and the following semicolon so I can tell which version I'm dealing with?

You want to use a capture group and get the second element of the array, which will give you the captured portion.

var stringAfterTrident = navigator.userAgent.match(/Trident([^;]+);/)[1];
//should return ["Trident/5.0;", "/5.0"] and you want the second item of the array

/Trident([^;]+);/ basically says starts with Trident, capture one or more character that is not the semicolon until there is a semicolon.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top