如何在JavaScript中验证URL地址?
要在JavaScript中验证URL地址,请使用“regex”,如以下代码所示。返回正确的URL地址为“true”,否则返回“false”
示例
<!DOCTYPE html> <html> <body> <script> var myURL; function validURL(myURL) { var 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}))'+ // ip (v4) address '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+ //port '(\\?[;&a-z\\d%_.~+=-]*)?'+ // query string '(\\#[-a-z\\d_]*)?$','i'); return pattern.test(myURL); } document.write(validURL("http://qries.com")); </script> </body> </html>