0

I am trying to get the value of a text input and check if there is any links in it and then take those links and make them into tags. But when I run this code, something is going wrong and it completely freezes the page. Basically, I want it to check for "http://" and if that exists, to keep on adding to the substr length until the end of the string/link. Is there a better way to do this?

// the id "post" could possibly say: "Hey, check this out! http://facebook.com"
// I'd like it to just get that link and that's all I need help with, just to get the      
// value of that entire string/link.
var x = document.getElementById("post");
var m = x.value.indexOf("http://");
var a = 0;
var q = m;

if (m != -1) {
    while (x.value.substr(q, 1) != " ") {
        var h = x.value.substr(m, a);
        q++;
    }
}
6
  • 2
    It's freezing because you've almost certainly got the potential for an infinite loop. Commented Oct 26, 2012 at 22:45
  • Also, your variables have terrible names. Code should be able to be looked at and roughly understood. This is not the case here. Commented Oct 26, 2012 at 22:47
  • The value of q never changes, so your loop condition never changes either, thus infinite loop. Commented Oct 26, 2012 at 22:48
  • Aren't you also missing a right brace "}"? Commented Oct 26, 2012 at 22:48
  • Indeed, your code is not complete. Commented Oct 26, 2012 at 22:49

1 Answer 1

3

Of course it is – there is an infinite loop.

You probably wanted to update the variable q in each iteration.

q = q + a;

or just q += a;

Update:

I see you changed the code a bit.

I get what you're trying to do. You're trying to get a URL from an input value.

Why don't you just use a simple RegExp instead of this unclear loop?

var match = x.value.match(/(?:^|\s)(http:\/\/\S+)/i);
var url = match ? match[1] : null;
Sign up to request clarification or add additional context in comments.

1 Comment

I just tried that, I am trying the link http :// facebook.com, it doesn't seem to work correctly. You can try if you want: zach.muny.us/widgets/youtube It appears to only go one letter after http://

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.