How to check if the url is true

0

I made this simple code to encode urls, but I would like it to work only with url checking if the protocol and hostname are correct or if the magnetic link is correct:

http://www.exemplo.com/
https://www.exemplo.com/
http://exemplo.com/
https://exemplo.com/
magnet:?xt=urn:btih:  //url magnético

function codificar() {
    var valor = document.getElementById("teste").value;
    var encode = window.btoa(valor);
    
    document.getElementById("saida").innerHTML = encode;
}
<p>Clique no botão para codificar a url.</p>
<br>
<input style='width:152px;' type="text" id="teste" value="http://www.exemplo.com">
<button onclick="codificar()">CODIFICAR</button>
<br>
<br>
<textarea style='width:150px; resize: none;' id="saida"></textarea>
    
asked by anonymous 26.07.2018 / 03:40

2 answers

3

You may be checking to see if your strings belong to a pattern using regex . Here is an example of a er (regular expression) and how it would look like:

  var re = new RegExp("^((http(s?):\/\/(www.)?[a-z]+.com\/)|(magnet:\?xt=urn:btih:))")

  var term = "http://www.exemplo.com/"

  if (re.test(term)) {
    alert("Valid");
  } else {
    alert("Invalid");
  }

As this er has been built, it will accept any string that begins with these patterns:

http://www.exemplo.com/
https://www.exemplo.com/
http://exemplo.com/
https://exemplo.com/
magnet:?xt=urn:btih:

That is, if you have this pattern at the beginning of string , anything that is after .com/ in url and btih: in magnet link will accept it. For example:

http://www.exemplo.com/qualquercoisaaquiassim/?-thiagorespondeu
    
26.07.2018 / 04:08
0

You can use this complete code below if you need .net co_de .org etc ... and it works perfectly with the magnetic url. It will check the expression, if it is invalid it will return an alert. If you need to add .xyz add here ftp , " (ftp|http|https) or | " is the logical operator corresponding to || .

function codificar() {
	var reg = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?|magnet:\?xt=urn:btih:/
	var valor = document.getElementById("teste").value;
	var encode = window.btoa(valor);

	if (reg.test(valor)) {
		document.getElementById("saida").innerHTML = encode;
	} else {
		alert("Url Invalido");
	}
}
<p>Clique no botão para codificar a url.</p>
<br>
<input style='width:152px;' type="text" id="teste" value="http://www.exemplo.com">
<button onclick="codificar()">CODIFICAR</button>
<br>
<textarea style='width:150px; resize: none;' id="saida"></textarea>
    
26.07.2018 / 07:10