开发者

jQuery - Check if input contents contains url on keyup

I'm trying to check whether an input contains a URL either when a user types the contents manually, pastes a link, or a combination of both. I'd like to fetch the URL's contents (similar to Facebook) when the first detection occurs.

So far I have the following:

$('#message').keyup(function() {

     var exp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; 
     if((this.value.match(exp))) {

      var match = exp.exec(this.value);
        alert(match[0]);
        $(this).unbind();
        return;
     }
  });

  $("#message").bind('paste', function(e) { $("#message").trigger('keyup'); });

This behaves properly when a link is pasted, when something is typed and then pasted, bu开发者_开发技巧t not when a url is typed manually.

If I go to type "http://www.stackoverflow.com", a match is triggered after "http://w".

What is a more intelligent way to write this behaviour?

EDIT: Just thought of something - what about testing the regex against the last thing the user typed that has a space before and after it?

Thanks,


While fetching a page on "paste" is a good option, I am really not sure if you want to fetch pages as user types them. A user could be typing a long URL which contains certain query string parameters that determine which page to render. Ideally you want the user to have finished typing the entire thing before you start sending out HTTP requests otherwise you would be fetching all sorts of intermediate pages which user doesn't want to (or need to!) see. For example

www.facebook.com

will obviously fetch the homepage however

www.facebook.com/britishpcrepairs

will fetch the page for a particular group on Facebook which is probably what your user wanted to see. So fetching the homepage was not really needed and would cause unnecessary confusions.

I think you should

  1. Fetch the page immediately on "paste"
  2. Fetch the page on blur after keypress has been recorded and no paste happened OR Fetch the page after a certain time out (say 2 seconds) after keypress has been recorded and no paste happened
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜