【发布时间】:2016-06-22 00:06:23
【问题描述】:
我正在使用这个正则表达式来匹配一个 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
【问题讨论】:
-
所以您想将使用 keyup 按下的键记录到一个字符串中,然后一旦该字符串完成,您想与之匹配吗?前面的文字是怎么回事?
-
你需要这个作为原生 javascript 吗?
-
对不起,我不清楚。我知道如何使用 JS 事件,我需要的是一个正则表达式,它丢弃额外的文本并识别输入的 URL 字符串的结尾。
标签: javascript regex events keyboard