JavaScript - DHTML / Strings
Detectando automaticamente as URLs contidas em um texto
enviado por Gabriel Fróes
Com este código, desenvolvido em Javascript é possível detectar e criar os links automaticamente de URLs contidas em um texto (string).
Esse código é extreamente útil, pois em diversas situações é preciso criar links quando o usuário digita uma URL. O efetio é semalhante ao que ocorre no Word quando se digita um endereço virtual.
Adicionei à função o parâmetro "targ" que se refere ao Target do link.
A URL será detectada tando iniciando por http:// quanto por www.
OBS: Este código é fácil de ser "transportado" para outra linguagem.
<html>
<head>
<title>Detectando automaticamente as URL contidas em um texto</title>
<script>
String.prototype.isUrl = function(targ){
this.ArrayTexto = this.split(" ");
this.tmpChar = "";
for (k=0; k<this.ArrayTexto.length; k++) {
this.idxUrl1 = this.ArrayTexto[k].slice(0,7);
this.idxUrl2 = this.ArrayTexto[k].slice(0,4);
if (this.idxUrl1 != "http://" && this.idxUrl2 != "www."){
this.tmpChar += this.ArrayTexto[k] + " ";
}
else{
this.Link = "";
if (this.idxUrl2 == "www.") this.Link = "http://";
this.Link += this.ArrayTexto[k];
if (this.Link.charAt(this.Link.length-1) == "."){
this.Link = this.Link.substring(0,this.Link.length-1);
}
this.tmpChar += "<a href=\"" + this.Link + "\" target=\"" + targ + "\">" + this.ArrayTexto[k] + "</a> ";
}
}
return this.tmpChar;
}
</script>
</head>
<body>
<script>
var texto = "Veja como é fácil gerar URLs automaticamente no site http://www.codigofonte.com.br/javascript. Entre também através do endereço www.codigofonte.com.br.";
document.write (texto.isUrl("_blank"));
</script>
</body>
</html>
Versão impressa gerada em:
quarta-feira, 25 de novembro de 2009
© Copyright 2006 - R&W Consulting.