简体   繁体   中英

Extract urls from string with JavaScript

I am working on a link preview script like fb uses it for example. The user creates a post that could potentially include links. On every keyup i test if the last key has been the space key and if that was the case i run my function:

function link_preview(event)
{
    var replyText = $("#answer_two").val();

    if(event.keyCode == 32)
    {
        var match = /^(?:[a-z]*?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/i.exec(replyText);

        if(match!="")
        {

            var preview = match[0];
        }
    }
}

So the user types a text that includes a link. When the link is detected a preview is shown with the information fetched from this url. The user has the option to close this preview and to add another link and this is exactly where my problems start. I can not access the second url and ignore the first. And all this gets even more complicated if a third url would be added to the mix. Has anyone a suggestion on how to work this?

Have you tried adding the global parameter to you're regex of "g" next to you're "i" at the end of your regex so it looked something like:

/^(?:[az]*?:\\/\\/)?([\\da-z\\.-]+)\\.([az\\.]{2,6})([\\/\\w \\.-]*)*\\/?$/gi

in this case you will get multiple matches across a string in which you will need to loop through.

reference at actual fix: http://jsfiddle.net/ps1rf1uw

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM