2011-10-20 14 views
5

Ok Digamos que tengo una URLURL de análisis con JavaScript o jQuery

example.com/hello/world/20111020 (con o sin la barra final). Lo que me gustaría hacer es eliminar de la URL el dominio example.com. y luego divide el mundo hello 20111020 en una matriz. Pero mi otro problema es Algunas veces la URL no tiene/hello/world/20111020 o simplemente/hello/así que primero necesito determinar si hay algo después de example.com si no hay, entonces no haga nada, ya que obviamente no hay nada con lo que trabajar. Sin embargo, si hay algo allí para cada/necesito agregarlo a esta matriz en orden. Entonces puedo trabajar con la matriz [0] y saber que fue hola.

Intenté algo hace un par de días pero me encontré con problemas con las barras inclinadas que seguían rompiendo el guión. Desafortunadamente, abandoné esa idea. Y hoy estoy buscando nuevas ideas.

Respuesta

14

Esto debería funcionar

var url = 'example.com/hello/world/20111020/'; 
//get rid of the trailing/before doing a simple split on/
var url_parts = url.replace(/\/\s*$/,'').split('/'); 
//since we do not need example.com 
url_parts.shift(); 

ahora url_parts apuntará a la matriz ["hello", "world", "20111020"].

+0

'var url = window.location.href;' para analizar la URL actual :) –

+0

Esto no funciona para mí. Solo obtengo example.com. – johnny

+0

@johnny Debe tomar los contenidos de la matriz 'url_parts' y no la salida del comando' url_parts.shift() ' –

3

Puede utilizar el plug-in jQuery-URL-Parser:

var file = $.url.attr("file"); 

En su caso, usted probablemente querrá utilizar segment():

var segments = $.url('http://allmarkedup.com/folder/dir/example/index.html').segment(); 

// segments = ['folder','dir','example','index.html'] 
2
<script type="text/javascript"> 
    function splitThePath(incomingUrl){ 
    var url = document.createElement("a"); 
    url.href = incomingUrl; 
    //url.hash Returns the anchor portion of a URL 
    //url.host Returns the hostname and port of a URL 
    //url.hostname Returns the hostname of a URL 
    //url.href Returns the entire URL 
    //url.pathname Returns the path name of a URL 
    //url.port Returns the port number the server uses for a URL 
    //url.protocol Returns the protocol of a URL 
    //url.search Returns the query portion of a URL 
    if(url.pathname && url.pathname != ""){ 
    var pathnameArray = url.pathname.split("/"); 
}else{ 

} 


} 
</script> 
+0

cuando configura el url.href se configura por primera vez, el navegador del cliente rellena el resto de los valores. – DefyGravity

0

He creado la siguiente expresión regular para las direcciones URL

^https?://(((0|([1-9][0-9]{0,1}))(\.(0|([1-9][0-9]{0,1}))){3})|([a-zA-Z]([a-zA-Z0-9$\[email protected]\.&+!*"\'\(\),]|(%[0-9a-fA-F][0-9a-fA-F]))*(\.([a-zA-Z]([a-zA-Z0-9$\[email protected]\.&+!*"\'\(\),]|(%[0-9a-fA-F][0-9a-fA-F]))*))*))(/|((/([a-zA-Z]([a-zA-Z0-9$\[email protected]\.&+!*"\'\(\),]|(%[0-9a-fA-F][0-9a-fA-F]))*))*))$ 

Ha sido escrito para MySql. Estoy seguro de que con un poco de manipulación usted puede conseguir que trabaje para sus necesidades.

BTW - Tomé la idea de un RFC - El número me escapa en este momento

+1

¿Qué diablos es eso? se ve impresionante – Squirrl

0

Para analizar URL, un enfoque diferente puede ser el uso del objeto DOM de anclaje.

var a = document.createElement("A"); 
a.href = 'http://example.com:8080/path/to/resources?param1=val1&params2=val2#named-anchor'; 

a.protocol; // http: 
a.host; // example.com:8080 
a.hostname; //example.com 
a.port; // 8080 (in case of port 80 empty string returns) 
a.pathname; // /path/to/resources 
a.hash; // #named-anchor 
a.search // ?param1=val1&params2=val2 
Cuestiones relacionadas