-2

I have this function to detect link:

function isValidUrl(urlString) {
    const pattern = new RegExp(
        '^([a-zA-Z]+:\\/\\/)?' + // protocol
        '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
        '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
        '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
        '(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
        '(\\#[-a-z\\d_]*)?$', // fragment locator
        'i'
    );
    return pattern.test(urlString);
}

It's working if the link is something like:

www.yahoo.com, http://www.google.com etc..

But if the link is :

let link1 = '//cdn.shopify.com/s/files/1/0033/3837/1190/products/SPL299_811f730c-5ae0-4d8e-846f-a4b970fc7081.jpg?v=1571142461';

let link2 = 'https://cdn.shopify.com/s/files/1/0033/3837/1190/products/SPL297_761368c2-ddd5-4b5e-ad21-95edc2aa35b8.jpg?v=1581525690;https://cdn.shopify.com/s/files/1/0033/3837/1190/products/SPL299_811f730c-5ae0-4d8e-846f-a4b970fc7081.jpg?v=1581525690;https://cdn.shopify.com/s/files/1/0033/3837/1190/products/SPL298_2116150c-2d8d-431a-a31a-7d337d540718.jpg?v=1581525690;https://cdn.shopify.com/s/files/1/0033/3837/1190/products/SPL300_27a827fc-11bd-4404-8217-c5046522dec2.jpg?v=1581525690';

then I can see this isValidUrl is returning false.

How can I fix it?

Shibbir
  • 1,963
  • 2
  • 25
  • 48

1 Answers1

0

I have slightly modified you regex to match your requirement.

function isValidUrl(urlString) {
    const pattern = new RegExp(
        '^(([a-zA-Z]+:)?\/\/)?' + // protocol
        '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
        '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
        '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port and path
        '(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
        '(\\#[-a-z\\d_]*)?$', // fragment locator
        'i'
    );
    return pattern.test(urlString);
}
let link1 = '//cdn.shopify.com/s/files/1/0033/3837/1190/products/SPL299_811f730c-5ae0-4d8e-846f-a4b970fc7081.jpg?v=1571142461';

let link2 = 'https://cdn.shopify.com/s/files/1/0033/3837/1190/products/SPL297_761368c2-ddd5-4b5e-ad21-95edc2aa35b8.jpg?v=1581525690;https://cdn.shopify.com/s/files/1/0033/3837/1190/products/SPL299_811f730c-5ae0-4d8e-846f-a4b970fc7081.jpg?v=1581525690;https://cdn.shopify.com/s/files/1/0033/3837/1190/products/SPL298_2116150c-2d8d-431a-a31a-7d337d540718.jpg?v=1581525690;https://cdn.shopify.com/s/files/1/0033/3837/1190/products/SPL300_27a827fc-11bd-4404-8217-c5046522dec2.jpg?v=1581525690';

console.log(isValidUrl(link1))
console.log(link2.split(';').every(isValidUrl))
Nishanth
  • 304
  • 3
  • 12