Parsing URLs with the DOM
2009-12-18 09:39
211 查看
This short function returns an object containing all possible information you would want to retrieve from a URL:
parseURL
// This function creates a new anchor element and uses location
// properties (inherent) to get the desired URL data. Some String
// operations are used (to normalize results across browsers).
function parseURL ( url ) {
var a = document. createElement ( 'a' ) ;
a.href = url ;
return {
source : url ,
protocol : a. protocol . replace ( ':' , '' ) ,
host : a. hostname ,
port : a. port ,
query : a. search ,
params : ( function ( ) {
var ret = { } ,
seg = a. search . replace ( /^/?/ , '' ) . split ( '&' ) ,
len = seg. length , i = 0 , s ;
for ( ; i < len ; i ++ ) {
if ( ! seg [ i ] ) { continue ; }
s = seg [ i ] . split ( '=' ) ;
ret [ s [ 0 ] ] = s [ 1 ] ;
}
return ret ;
} ) ( ) ,
file : ( a. pathname . match ( ///([^//?#]+)$/i ) || [ , '' ] ) [ 1 ] ,
hash : a. hash . replace ( '#' , '' ) ,
path : a. pathname . replace ( /^([^//])/ , '/$1' ) ,
relative : ( a. href . match ( /tps?:////[^//]+(.+)/ ) || [ , '' ] ) [ 1 ] ,
segments : a. pathname . replace ( /^/// , '' ) . split ( '/' )
} ;
}
Usage
var myURL = parseURL ( 'http://abc.com:8080/dir/index.html?id=255&m=hello#top' ) ;
myURL. file ; // = 'index.html'
myURL. hash ; // = 'top'
myURL. host ; // = 'abc.com'
myURL. query ; // = '?id=255&m=hello'
myURL. params ; // = Object = { id: 255, m: hello }
myURL. path ; // = '/dir/index.html'
myURL. segments ; // = Array = ['dir', 'index.html']
myURL. port ; // = '8080' myURL. protocol ; // = 'http'
myURL. source ; // = 'http://abc.com:8080/dir/index.html?id=255&m=hello#top'
相关文章推荐
- Parsing URLs with the DOM
- Parsing URLs with the DOM
- Parsing URLs with the DOM!
- XML学习札记--Parsing the DOM
- [Javascript] Manipulate the DOM with the classList API
- 12 How does XML fit with the DOM?
- Parsing the XML DOM
- Tomcat404错误:All URLs used to access the Manager application should now start with one of the followi
- Php tutorial : Parsing html with Domdocument
- [RxJS] Reactive Programming - Rendering on the DOM with RxJS
- Working with the DOM
- mysql启动报错:Another MySQL daemon already running with the same unix socket.
- 在Archive项目 时,出现了“Yourbuild settings specify a provisioning profile with the UUID “”
- Parsing XML Files with PowerShell
- Handler crashed with error can't find templatefile in the path 解决方法
- The Trouble With Multicore
- MySQL数据库执行sql语句创建数据库和表提示The 'InnoDB' feature is disabled; you need MySQL built with 'InnoDB' to have
- Stone and His War with the Undead
- Resource is out of sync with the file system解决办法
- Understanding what the WITH ROLLBACK IMMEDIATE does