使用JS或Jquery检测textarea中的url [英] Detect url in textarea with JS or Jquery
问题描述
如果用户已完成输入网址,请检查(在textarea或其他输入中),如果Facebook以其主要形式输入网址吗?
How to detect (in a textarea or others inputs) if the user has finished to enter a url as Facebook does in its main form please ?
< a href =https://stackoverflow.com/questions/7705501/jquery-detect-and-validate-an-url>此工作,但仅在用户完成输入并执行操作时才会起作用,例如单击一个按钮。
Solutions like this work but only when the user has finished typing and performs an action, eg clicking a button.
我希望在整个条目中检测网址,例如检查每个空格后输入的单词。
I will wish to detect urls throughout the entry, eg run a check on the word that has been typed after each space.
提前谢谢。
推荐答案
以下是如何执行此操作的示例:
Here is an example on how you could do this:
$(function() {
"use strict";
var url = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
$("#textarea").on("keyup", function( e ) {
var urls, output = "";
if ( e.keyCode !== 8 && e.keyCode !== 9 && e.keyCode !== 13 && e.keyCode !== 32 && e.keyCode !== 46 ) {
// Return is backspace, tab, enter, space or delete was not pressed.
return;
}
while ((urls = url.exec(this.value)) !== null) {
output += urls[0] + ", ";
}
console.log("URLS: " + output.substring(0, output.length - 2));
});
});
当然,您必须绑定其他事件,例如 .blur()
,以使其正常工作。
Of course you would have to bind other events like .blur()
for it to work properly.
尝试以下小提琴,并在键入时检查控制台: http://jsfiddle.net/sQVe/mXQrc/1/
Try the following fiddle and check you console as you type: http://jsfiddle.net/sQVe/mXQrc/1/
这篇关于使用JS或Jquery检测textarea中的url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!