-1

I'm using Javascript to parse the following User-Agent string:

"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0"

I'd like to extract the word "Windows" between the first parenthesis and a space. How can I use regular expressions in Javascript to do this?

Brinley
  • 591
  • 2
  • 14
  • 26
  • 1
    I feel like regex isn't the best way to do this. Since you just want the word after the first parenthesis, you could find the first instance of `(`, then find the first instance of `[space]` after it, and then take the substring between them. – Thomas Cohn Jun 14 '18 at 17:34
  • If you are looking to perform operations on the User-agent string then I would suggest a battle-tested library might be more suitable than regex. – John Jun 14 '18 at 17:45
  • Maybe it helps: [Detecting OS Windows](https://stackoverflow.com/a/27862868/6188402) – Washington Guedes Jun 14 '18 at 19:01

2 Answers2

0

If you only one the first word after the first parentheses you can use this regex: /\((\w+)/g

var string = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0";

console.log(/\((\w+)/g.exec(string)[1] || 0)
0

You can use String.match():

// Your input string
const string = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0';

// Find string
const match = string.match(/\((.+?)\s/);

// If string was found
if (match !== null) {
  // Get the result
  // match[0] is this whole matched string
  // match[1] is just the matched group
  const result = match[1];
  
  // So something with the result
  console.log(result);
}
user3210641
  • 1,565
  • 1
  • 10
  • 14