Home > Software engineering >  How to check for a valid URL in javascript
How to check for a valid URL in javascript

Time:11-19

Hi I am trying to write a function that will test for a valid URL I found this

 const pattern = new RegExp(
      '^(https?:\\/\\/)?'   // 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_]*)?$',
      'i'
    ); // fragment locator

However it has a false positive it return true when I call it with http://something I need to check that url has a top level domain as well has a protocol .org. Any help would be much appreciated.

CodePudding user response:

try this code

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

const yourUrl = 'http://google.com';
const wrongUrl = 'http://google';
console.log(isValidUrl(yourUrl)); //true
console.log(isValidUrl(wrongUrl)); //false

CodePudding user response:

function isValidUrl(str) {
      const pattern = new RegExp(
        '^(https?:\\/\\/)?'   // 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(str);
    }

    console.log(isValidUrl('https://stackoverflow.com')); // true
    console.log(isValidUrl('app://stackoverflow.com')); // false
    console.log(isValidUrl('stackoverflow')); // false

CodePudding user response:

const url = new URL('http://....');

  • Related