正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。

正则表达式是由普通字符(例如字符 a 到 z)以及特殊字符(称为"元字符")组成的文字模式。模式描述在搜索文本时要匹配的一个或多个字符串。正则表达式作为一个模板,将某个字符模式与所搜索的字符串进行匹配。

本文利用了正则表达式来验证网址URL

(正则表达式中的“-”只是将每个部分隔离出来为了更好的展示效果罢了,应用时需要将之去掉)

话不多说,直接上代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>URL</title>
</head>
<body>
    <script>
        // https://1级域名.<n级域名>.1级后缀.<n级后缀>-<路径1/路径n>-<?参数名1=参%数%值1&参数名n=参%数%值n> */
        // https://  my-blog123.126ease    /news/sports-news  ?a=123&bb=你妹@!#$%^*()_+       
        // var regUrl = /^(协议段)?-(域名段)-(后缀段)-(路径段)-(参数段)?$/
        // var regUrl = /^(https?:\/\/)?-((\w+)+(\.\w+)*)-((\.[a-z]+)+)-((\/\w+)*)-(\?(\w+\=.+?)(&\w+\=.+?)*)?-(#\w+)?$/
        var regUrl = /^(https?:\/\/)?-((\w+)+(\.\w+)*)-((\.[a-z]+)*)-((\/\w+)*)-(\?\w+\=([\w\u4e00-\u9fa5!@#\$%\^&\*\(\)_\+]+)(&\w+\=([\w\u4e00-\u9fa5!@#\$%\^&\*\(\)_\+]+))*)?-(#\w+)?$/

        console.log(regUrl.test("http://-blog.sina--/path/path-?a=123&bb=你妹@!#$%^*()_+-#abc"));//true
        console.log(regUrl.test("http://-blog.sina--/path/path-?a=123&bb=你妹@!#$%^*()_+-"));//true
        console.log(regUrl.test("https://-blog.sina--/path/path-?a=123&bb=你妹@!#$%^*()_+-"));//true
        console.log(regUrl.test("https://-localhost--/path/path-?a=123&bb=你妹@!#$%^*()_+-"));//true
        console.log(regUrl.test("https://-blog---?a=123&bb=你妹@!#$%^*()_+-"));//true
        console.log(regUrl.test("https://-weibo----"));//true
        console.log(regUrl.test("httpxs://-blog.sina-/path/path-?a=123&bb=你妹@!#$%^*()_+"));//false
        console.log(regUrl.test("https://-blog你妹-.nimei-/path/path-"));//fasle
        console.log(regUrl.test("https://-blog-.COM.CN-/path/path-?a=123"));//false
        console.log(regUrl.test("https://-blog-.nimei-/pa@th/path-?a=123&bb=你&妹@!#$%^*()_+"));//false
        console.log("");

        // /* 将协议、域名、后缀、路径、请求参数 */
        var url = "http://-blog.sina--/path/path-?a=123&bb=你妹@!#$%^*()_+-#abc"
        var arr = regUrl.exec(url)
        console.log("协议",arr[1]);
        console.log("域名",arr[2]);
        console.log("后缀",arr[5]);
        console.log("路径",arr[7]);
        console.log("参数",arr[9]);
        console.log("哈希",arr[13]);
        
    </script>
</body>
</html>

更多推荐

用正则表达式来验证IP网址URL