如何在 javascript 中检查有效 URL

问题描述 投票:0回答:3

嗨,我正在尝试编写一个函数来测试我发现的有效 URL

 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

但是,当我使用

true
调用它时,它会返回
http://something
,我需要检查 url 是否具有顶级域以及协议
.org
。任何帮助将不胜感激。

javascript regex
3个回答
1
投票

试试这个代码

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

0
投票

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


-2
投票

   const validateUrl = (arg) => {
try {
    new URL(arg);
} catch (e) {
    // throw new Error(e); (uncomment if debugging)
    return false;
}
return true;
}

console.log(validateUrl("https://google.com")); // true
const validateUrl = (arg) => { try { new URL(arg); } catch (e) { // throw new Error(e); (uncomment if debugging) return false; } return true; } console.log(validateUrl("https://google.com")); // true
© www.soinside.com 2019 - 2024. All rights reserved.