1

I am trying to write a regex to get the string between v= and &t so in the case below I would get 1oDaF770-ws

// I want to get 1oDaF770-ws from the url below

const url = "https://www.youtube.com/watch?v=1oDaF770-ws&t=67s"

I have the following code

const url = "https://www.youtube.com/watch?v=1oDaF770-ws&t=67s"
url.match(/(?<=v=\s*).*?(?=\s*&t=)/gs);

As you can see I have followed the answer here but unfortunately it doesn't seem to work for me.

peter flanagan
  • 9,195
  • 26
  • 73
  • 127

1 Answers1

1

I'd suggest not using a regex at all for this. It will no longer work if the order of query parameters happens to change.

You can just parse the URL and get the required query parameter:

const url = new URL('https://www.youtube.com/watch?v=1oDaF770-ws&t=67s');
const v = url.searchParams.get('v');

console.log(v);
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156