[英]How can I regexp match a URL from an onKeyDown event
我正在使用此RegExp来匹配URL
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
这适用于纯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事件,然后在输入值与您的正则表达式匹配时更新状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.