我如何regexp匹配onKeyDown事件中的URL

时间:2016-03-08 06:40:34

标签: javascript regex events keyboard

我正在使用此RegExp来匹配网址

 reMatchUrl = /(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?/i

但是,在键入或复制/粘贴时,如何修改RegExp以匹配input[type=textarea]元素中的URL? (即来自onKeyUp事件)

挑战是等到URL完成(检查尾随空格?),还要正确处理包含URL的复制/粘贴块。但如果字符串以url结尾,则不会有尾随空格......

示例:

// match only the url in the string, 
// recognizing that the URL is complete
string = "hey, check this out http://www.something.com/this/is/cool?a=b"
found = string.match(reMatchUrl)
url = found && found[0]
// url = "http://www.something.com/this/is/cool?a=b"

// does NOT match the url in the string because the user 
// has NOT finished typing
string = "hey, check this out http://www.something.com/this/is/coo"
found = string.match(reMatchUrl)
url = found && found[0]
// url = null

1 个答案:

答案 0 :(得分:0)

这适用于纯JS:

<!DOCTYPE html>
<html>
<body>
    <label for="url">set an url:</label>
    <input type="text" id="url">
    <br><br>
    <div id="result"></div>
    <script>
        // regex string
        var reMatchUrl = '(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?';
        // build regex matched
        var regx = new RegExp(reMatchUrl, 'i');

        // add event listener on input
        document.getElementById('url').addEventListener("keyup", function (e) {
            // get the text in the input
            var input = document.getElementById('url').value;

            // check for a match
            var match = input.match(regx);

            // update html
            if (match) {
                document.getElementById('result').innerHTML =  'valid';
            } else {
                document.getElementById('result').innerHTML =  'not valid';
            }
        });

    </script>
</body>
</html>

它会侦听输入上的Key Up事件,如果输入值与正则表达式匹配,则会更新状态。