2

I have a textbox where the user can enter URL and button named Check link. On clicking button, a new window should be opened with the URL entered by the user. If i enter URL as "http://google.com" then window.open('http://google.com'); is working fine but if i enter "www.google.com" then it is appending to the current window url (http://localhost:1234www.google.com) which is not a valid url. How to make this work?

Thanks in advance

0

4 Answers 4

2

Check & prepend

if (!/^(http:|https:)/i.test(url))
   url = "http://" + url;
Sign up to request clarification or add additional context in comments.

Comments

1

try this:

function f(url) {
    if (url.indexOf("http://") == -1) {
        url = "http://" + url;
    } 
    window.open(url);
}

2 Comments

Thanks for the reply.. I solved in this way but by using regx to check http exists or not. It looks weird in this way. just trying for other ways. I am not understanding what causing the issue?
Good one from my point of view simply because we are not waisting resource on a regular expression when it's not needed. For the same result this has a low level of complexity if you compare to regex.
0

If your question is "How do I test if a string starts with 'http://' and if not prepend it?" then something like this:

var url = "somestring.com"; // as set from your textbox
if (0 != url.toLowerCase().indexOf("http"))
   url = "http://" + url;

It would be wise to trim leading and trailing spaces before doing this test, but I'll leave that as an exercise for the reader...

Comments

0

Add a onclick button function and handle the text in that.

function checkLink() {
    var url = document.getElementById("textbox-id").value;
   if(url.substr(0,7) != "http://") {
       alert("Invalid URL! Please make it like http://myurl.com");
    return false;
   }
}

Comments

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.