Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

javascript - Detect url in textarea with JS or Jquery

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 ?

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.

Thank you in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}(/[-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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...