panji gemilang
panji gemilang

Reputation: 809

Regex get only the first occurance in Javascript

I have this line :

"Internal": "128 6GB RAM, 128 8GB RAM"

and I wanted to get only the first 6GB RAM so I tried this :

^(\dGB RAM)

that doesn't match anything, if I removes the ^() it matches all the 6GB RAM & 8GB RAM.

I tried it on https://regexr.com/ website

Upvotes: 0

Views: 38

Answers (2)

Loi Nguyen Huynh
Loi Nguyen Huynh

Reputation: 9928

  • /\dGB RAM/g with the flag g (global) will match 6GB RAM and 8GB RAM
  • but only /\dGB RAM/ without the g flag will only match 6GB RAM

You saw it matched both 6GB RAM and 8GB RAM because regexr.com adds global flag as default, turn it off and you'll only see it matches 6GB RAM.

enter image description here

Upvotes: 1

alex067
alex067

Reputation: 3281

I absolutely hate regex, so you can do something like this:

first_ram = internal.split(",")[0]

Upvotes: 0

Related Questions