国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

一個非常全面的javascript URL解析函數和分段URL解析方法

2019-11-20 20:50:19
字體:
來源:轉載
供稿:網友

一、URL解析函數

復制代碼 代碼如下:

<script> 
/**
*@param {string} url 完整的URL地址
*@returns {object} 自定義的對象
*@description 用法示例: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'

*/ 
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('/') 
 }; 
}   

//var myURL = parseURL('http://abc.com:8080/dir/index.html?id=255&m=hello#top'); 
var myURL = parseURL('http://localhost:8080/test/mytest/toLogina.ction?m=123&pid=abc'); 
alert(myURL.path); 
alert(myURL.params.m); 
alert(myURL.params.pid); 
</script>

二、JS分段URL解析

URL : 統一資源定位符 (Uniform Resource Locator, URL)
完整的URL由這幾個部分構成:scheme://host:port/path?query#fragment

復制代碼 代碼如下:

scheme  = 通信協議 (常用的http,ftp,maito等)
host = 主機 (域名或IP)
port = 端口號
path = 路徑
query = 查詢(可選,用于給動態網頁(如使用CGI、ISAPI、PHP/JSP/ASP/ASP.NET等技術制作的網頁)傳遞參數,可有多個參數,用”&”符號隔開,每個參數的名和值用”=”符號隔開。)
fragment = 信息片斷(字符串,用于指定網絡資源中的片斷。例如一個網頁中有多個名詞解釋,可使用fragment直接定位到某一名詞解釋。(也稱為錨點.))

對于這樣一個URL
//m.survivalescaperooms.com:80/seo/?ver=1.0&id=6#imhere

我們可以用javascript獲得其中的各個部分
1, window.location.href
整個URl字符串(在瀏覽器中就是完整的地址欄)

2,window.location.protocol
URL 的協議部分
本例返回值:http:

3,window.location.host
URL 的主機部分
本例返回值:m.survivalescaperooms.com

4,window.location.port
URL 的端口部分
如果采用默認的80端口(update:即使添加了:80),那么返回值并不是默認的80而是空字符
本例返回值:”"

5,window.location.pathname
URL 的路徑部分(就是文件地址)
本例返回值:/seo/

6,window.location.search
查詢(參數)部分
除了給動態語言賦值以外,我們同樣可以給靜態頁面,并使用javascript來獲得相信應的參數值
本例返回值:?ver=1.0&id=6

7,window.location.hash
錨點
本例返回值:#imhere

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 会昌县| 皋兰县| 奉贤区| 卢湾区| 色达县| 巨野县| 兰考县| 柏乡县| 林州市| 临澧县| 清镇市| 友谊县| 吕梁市| 泰州市| 饶阳县| 绥宁县| 上栗县| 山丹县| 东平县| 鹿邑县| 新和县| 衡南县| 思茅市| 翼城县| 大兴区| 浦江县| 漯河市| 铜鼓县| 福安市| 新乡市| 介休市| 泸溪县| 刚察县| 黄大仙区| 罗田县| 石泉县| 桐城市| 衡水市| 延吉市| 三门峡市| 延寿县|