Home > OS >  How to use regex in react
How to use regex in react

Time:12-16

I have a URL like this

https://play.google.com/store/apps/details?id=in.swiggy.android&hl=en_IN&gl=US

So here you can see there is a parameter called id. I need to get the value of id (value after id=)and (it stops at &)

So ideal output should look like this in.swiggy.android.

I wrote regex like this but my output looks like this

id=in.swiggy.android. Here I don't need "id=" in the output. As you can see it stop just before &. So 2nd part is working fine.


let regex = /id=([^&]*)/;
 let value  = (regex.exec((url))[0]);``

CodePudding user response:

You almost reached the goal.
Actually either you have to enclose id= into Positive lookbehind so your regexp turns into (?<=id=)([^&]*)
or just retrive 1st [1] element of match result instead of [0].

let regex = /id=([^&]*)/;  
let value  = (regex.exec((url))[1]);  

Second approach works fine as well because you captured [^&]* into parentheses so it can be got as separate value.

  • Related