简体   繁体   中英

How to Check if User entered text contains http:// in Javascript

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

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();
}

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM