La mejor manera de parsear URLs con Javascript

Uno de mis trucos favoritos de JavaScript de todos los tiempos es una técnica para parsear direcciones URL en distintas partes (host, ruta, cadena de consulta, etc.) que no requiere de ninguna librería o expresión regular avanzada. Para ello solo se utiliza la potencia de DOM, y, más precisamente, del elemento de anclaje a.

Como parte de un conjunto de propiedades regulares que los navegadores asignan a los elementos de anclaje, hay unos cuantos que imitan las propiedades del objeto location. Echa un vistazo:

JS

$(function(){

    // The URL we want to parse
    var url = 'http://tutorialzine.com/2013/07/quick-tip-parse-urls/?key=value#comments';

    // The magic: create a new anchor element, and set the URL as its href attribute.
    // Notice that I am accessing the DOM element inside the jQuery object with [0]:
    var a = $('', { href:url } )[0];

    $('#host').val(a.hostname);
    $('#path').val(a.pathname);
    $('#query').val(a.search);
    $('#hash').val(a.hash);

    // Even more:
    // a.port, a.protocol,
    // a.origin (not available in older IE versions)

});

HTML

<ul>
    <li><label for="host">Host:</label> <input type="text" id="host" /></li>
    <li><label for="path">Path:</label> <input type="text" id="path" /></li>
    <li><label for="query">Query String:</label> <input type="text" id="query" /></li>
    <li><label for="hash">Hash:</label> <input type="text" id="hash" /></li>
</ul>

CSS

html{
    background-color:#f4f4f4;
    font:14px/1.4 sans-serif;
    color:#666;
}

ul{
    list-style:none;
    width:300px;
    margin:50px auto;
}

li{
    padding:4px;
}

input{
    font:inherit;
    border:1px solid #ccc;
    border-radius:2px;
    padding:2px 5px;
}

label{
    width:90px;
    display:inline-block;
    text-align:right;
}

Uso jQuery aquí por comodidad, pero puedes utilizar de la misma manera Javascript puro creando el elemento de anclaje con var a = document.createElement('a'), y luego asignándolo a la URL del a.href directamente.

Y aquí tienes un ejemplo un poco más complejo, que te permite escribir la URL en un campo de texto y parsearla en tiempo real:

JS

$(function(){

    // Cache the fields
    var url = $('#url'), host = $('#host'), path = $('#path'), 
        query = $('#query'), hash = $('#hash');

    // Listen for the input event and update the fields

    url.on('input', function(){
        var a = $('', { href:url.val() } )[0];

        host.val(a.hostname);
        path.val(a.pathname);
        query.val(a.search);
        hash.val(a.hash);
    });

    // Set a default URL 
    url.val('http://tutorialzine.com/2013/07/quick-tip-parse-urls/?key=value#comments');

    // Trigger the input event
    url.trigger('input');
});

HTML

<div>
    <label for="url">Enter a URL:</label> <input type="text" id="url" size="50" />
</div>

<ul id="parts">
    <li><label for="host">Host:</label> <input type="text" id="host" /></li>
    <li><label for="path">Path:</label> <input type="text" id="path" /></li>
    <li><label for="query">Query String:</label> <input type="text" id="query" /></li>
    <li><label for="hash">Hash:</label> <input type="text" id="hash" /></li>
</ul>

CSS

html{
    background-color:#f4f4f4;
    font:14px/1.4 sans-serif;
    color:#666;
}

ul{
    list-style:none;
    width:300px;
    margin:0 auto;
}

li{
    padding:4px;
}

input{
    font:inherit;
    border:1px solid #ccc;
    border-radius:2px;
    padding:2px 5px;
}

label{
    width:90px;
    display:inline-block;
    text-align:right;
}

div{
    padding:40px;
    text-align:center;
}

La única diferencia importante aquí es que estoy escuchando el evento del input (no soportado en versiones de IE superiores, tendrás que utilizar keypress en su lugar) que notifica al detector de eventos de cada cambio de valor del campo.

Enlaces externos con estilo diferente

Una práctica útil mediante esta técnica es el tratamiento de enlaces externos de manera diferente. Puedes agregar un icono al lado de cada enlace que apunte fuera de tu sitio web, o incluso puedes mostrar algún tipo de página intermedia que alerte a los visitantes que están siendo redirigidos a un sitio web de terceros. Para detectar los enlaces externos, vamos a comparar la propiedad del host del elemento DOM y el objeto location:

JS

$(function(){

    // Get only the external links:
    var external = $('a[href]').filter(function(){
        return this.hostname != location.hostname;
    });

    // In the return above, you may also compare the protocol 
    // property if you wish to distinguish http from https links.

    external.addClass('external');

});

HTML

<a href="?page=123">Page 1</a>
<a href="/page2.html">Page 2</a>
<a href="http://demo.tutorialzine.com/">Page 3</a>
<a href="http://tutorialzine.com/page3.html">Page 4</a>
<a href="http://google.com/">Page 5</a>

CSS

html{
    background-color:#f4f4f4;
    font:15px/1.4 sans-serif;
    color:#666;
}

body{
    padding:50px;
    text-align:center;
}

a{
    color:#999;
}

a.external{
    color:green;
}

a.external:after{
    content:' ⇲';
}

Y este ha sido el artículo en el que trataba explicaros la mejor manera de parsear URLs con Javascript, esperamos que te haya gustado y sepas aplicarlo en tus futuros proyectos. Ya sabes que si nos quieres proponer un tema que quieres ver reflejado como un tutorial o como una práctica, solo tienes que hacer uso del área de comentarios de un poco más abajo. Por el contrario, si quieres enviarnos tus propios tutoriales, puedes hacerlo a través de la intranet de usuarios que está habilitada para ello, a través del menú Enviar Tutorial. Ya sabes, ayúdanos a crecer con tus conocimientos. ¡Un saludo y feliz código!

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP