Search code examples
javascriptregexurlstring-parsingquery-string

Javascript regex parse complex url string


I need to parse a complex URL string to fetch specific values.

From the following URL string:

/api/rss/feeds?url=http://any-feed-url-a.com?filter=hot&format=rss&url=http://any-feed-url-b.com?filter=rising&format=rss

I need to extract this result in array format:

['http://any-feed-url-a.com?filter=hot&format=rss', 'http://any-feed-url-b.com?filter=rising&format=rss']

I tried already with this one /url=([^&]+)/ but I can't capture all correctly all the query parameters. And I would like to omit the url=.

RegExr link

Thanks in advance.


Solution

  • This regex works for me: url=([a-z:/.?=-]+&[a-z=]+)

    also, you can test this: /http(s)?://([a-z-.?=&])+&/g

    Example

    const string = '/api/rss/feeds?url=http://any-feed-url.com?filter=hot&format=rss&url=http://any-feed-url.com?filter=latest&format=rss'
    
    const string2 = '/api/rss/feeds?url=http://any-feed-url.com?filter=hot&format=rss&next=parm&url=http://any-feed-url.com?filter=latest&format=rss'
    
    const regex = /url=([a-z:/.?=-]+&[a-z=]+)/g;
    const regex2 = /http(s)?:\/\/([a-z-.?=&])+&/g;
    
    console.log(string.match(regex))
    console.log(string2.match(regex2))