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?
Try this:
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 onlyin 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< 0you’re creating a global variable (
b) for no reasondon’t escape – as xdevel said in his comment, this will mean you check for an encoded version of the string, not the string itself