Di1997
Di1997

Reputation: 129

JS function stuck in loop

So, here's my function: It's supposed to extract links from input. (start at http or something like that and end at " "). The problem is that I can't debug how well this function works, because it stucks in loop. I've tried to check the reason why, still can't tell.

 function linkify(input)
    {
        if (input === undefined || input == null)

        return input;

        var tinput = input;
        var urlextr = "";
        var url = [""];
        var num = 0;

        //search for "http://" first
        while(tinput.match(/http:\/\//gi) != null)
        {
            console.log("http");
            urlextr=tinput.substring(tinput.search("http://"));
            urlextr=urlextr.substring(0,urlextr.search(" "));
            url[num] = urlextr;
            url[num+1] = urlextr;
            num = num + 2;
            tinput = tinput.replace(urlextr,"");
        }

        //search for "https://"
        while(tinput.match(/https:\/\//gi) != null)
        {
            console.log("https");
            urlextr=tinput.substring(tinput.search("https://"));
            urlextr=urlextr.substring(0,urlextr.search(" "));
            url[num] = urlextr;
            url[num+1] = urlextr;
            num = num + 2;
            tinput = tinput.replace(urlextr,"");
        }

        //search for "ftp://" (Why not?)
        while(tinput.match(/ftp:\/\//gi) != null)
        {
            console.log("ftp");
            urlextr=tinput.substring(tinput.search("ftp://"));
            urlextr=urlextr.substring(0,urlextr.search(" "));
            url[num] = urlextr;
            url[num+1] = urlextr;
            num = num + 2;
            tinput = tinput.replace(urlextr,"");
        }

        //search for "www.*" (Must be last!)
        while(tinput.match(/www./gi) != null)
        {
            console.log("www");
            urlextr=tinput.substring(tinput.search("www."));
            urlextr=urlextr.substring(0,urlextr.search(" "));
            url[num] = urlextr;
            url[num+1] = urlextr;
            num = num + 2;
            tinput = tinput.replace(urlextr,"");
        }
        console.log(url);
        return output;
    }

Upvotes: 0

Views: 205

Answers (1)

mic4ael
mic4ael

Reputation: 8290

I assume you have a string in which you have different urls separated with a space. The problem lies in

urlextr=urlextr.substring(0,urlextr.search(" "));

In case you are processing the last URL in your string it will always return an empty string, thus making the loop run indefinitely. To fix it you could do sth like below

urlextr=tinput.substring(tinput.search("http://"));
urlextr=urlextr.substring(0,urlextr.search(" "));
if (!urlextr) {
    url[num] = tinput.trim();
    break;
}
url[num] = urlextr;
url[num+1] = urlextr;

Upvotes: 2

Related Questions