1

I have a setup like, My website ask the user for entering a URL. Sometimes user enters like http://google.com/ and other times google.com, but my application supports URL with http:// or https://,
I tried this:

var a = document.getElementById('tinput').value;
if (a.indexOf(escape('http://')) < 0 && a.indexOf(escape('https://')) < 0){
b = 'http://' + a;
document.getElementById('tinput').value = b;
}
document.getElementById("urlfrm").submit();

But this dint work. It always adds http:// to all the URL even if they contain the same. What to do?

1
  • 1
    did you try removing escape() ? because it converts your https:// into https%3A// Commented Jul 3, 2012 at 9:19

3 Answers 3

2

Try

var a = document.getElementById('tinput').value;
if (a.indexOf('http://') == -1 && a.indexOf('https://') == -1){
b = 'http://' + a;
document.getElementById('tinput').value = b;
document.getElementById("urlfrm").submit();
} else {
document.getElementById("urlfrm").submit();
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

var field = document.getElementById('tinput');
if (!/^https?:\/\//.test(field.value)) field.value = 'http://'+field.value;

A couple of points to note:

  • your current check allows for http(s):// to be anywhere in the string - you should check for it at the start only

  • in the interests of code readability, and because the only value under zero that indexOf() can return is -1, it's better to check for that explicitly, rather than < 0

  • you're creating a global variable (b) for no reason

  • don't escape - as xdevel said in his comment, this will mean you check for an encoded version of the string, not the string itself

Comments

0

You can do this simply with regular expressions, well worth learning about them.

if ( a.match("^https?://") ) {
    alert("a is a url");
}

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.