Detect url in textarea with JS or Jquery

我只是一个虾纸丫 提交于 2019-12-01 01:32:46

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));
    });
});

Of course you would have to bind other events like .blur() for it to work properly.

Try the following fiddle and check you console as you type: http://jsfiddle.net/sQVe/mXQrc/1/

Look at this: https://github.com/stephan-fischer/jQuery-LiveUrl/ - its clean, simple, and provides a preview of the url!

What you are looking for is the keypress event, you can view the documentation and an example of how to use it here: http://api.jquery.com/keypress/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!