Home > front end >  Unable to extract text after matching a phrase in input string
Unable to extract text after matching a phrase in input string

Time:07-06

I'm trying to extract a URL from a string. The input is something like this:

const str = `/div><img src="https://server_url.com/assets/image.jpg&size=800x600"></img><div`;

But when I try to get the URL, I get null:

const match = str.match(/https:\/\/server[a-zA-Z]{1,}&size=[0-9]{1,}x[0-9]{1,}/g) // returns null
//                                                   ^^^^^^^^^^^^^^^^^^^^^^^^^
//                              I do this, because the size is not always 800x600

What am I doing wrong here?

Doing just the following works:

const match = str.match(/https:\/\/server/g)

CodePudding user response:

You are not matching all the possible the characters after server.

In Javascript you can write [0-9]{1,} as \d to match 1 or more digits.

https:\/\/server[^&\s]*&size=\d x\d 

regex demo

If there can be more parameters, you can exclude matching the " instead:

https:\/\/server[^\s"]*&size=\d x\d 

Regex demo

  • Related