用 Javascript 解析鏈接(URL)是一個常見的需求,本文介紹了一個非常健全的用 Javascript 寫的鏈接(URL)解析類,他可以準確獲取一個完整的 URL 中每個部分的內容,包括協議、URL中包含的用戶名和密碼、主機名、端口、路徑名、參數、錨點(Fragment Anchor)等信息。
- <body>
- <div id="example">
- <div id="example_main">
- <script type="text/javascript">
- if (typeof Poly9 == 'undefined')
- {
- var Poly9 = {};
- }
- Poly9.URLParser = function(url) {
- this._fields = {
- 'Username' : 4,
- 'Password' : 5,
- 'Port' : 7,
- 'Protocol' : 2,
- 'Host' : 6,
- 'Pathname' : 8,
- 'URL' : 0,
- 'Querystring' : 9,
- 'Fragment' : 10
- };
- this._values = {};
- this._regex = null;
- this.version = 0.1;
- this._regex = /^((/w+):////)?((/w+):?(/w+)?@)?([^///?:]+):?(/d+)?(//?[^/?#]+)?/??([^#]+)?#?(/w*)/;
- for(var f in this._fields)
- {
- this['get' + f] = this._makeGetter(f);
- }
- if (typeof url != 'undefined')
- {
- this._parse(url);
- }
- }
- Poly9.URLParser.prototype.setURL = function(url) {
- this._parse(url);
- }
- Poly9.URLParser.prototype._initValues = function() {
- for(var f in this._fields)
- {
- this._values[f] = '';
- }
- }
- Poly9.URLParser.prototype._parse = function(url) {
- this._initValues();
- var r = this._regex.exec(url);
- if (!r) throw "DPURLParser::_parse -> Invalid URL";
- for(var f in this._fields) if (typeof r[this._fields[f]] != 'undefined')
- {
- this._values[f] = r[this._fields[f]];
- }
- }
- Poly9.URLParser.prototype._makeGetter = function(field) {
- return function() {
- return this._values[field];
- }
- }
- var url = 'http://user:password@www.49028c.com:1234/test/test.asp?id=1#test';
- var p = new Poly9.URLParser(url);
- document.write("<strong>URL:</strong> " + url + "<br><br>");
- document.write("解析結果如下:<br><br>");
- document.write("<strong>協議:</strong> " + p.getProtocol() + "<br>");
- document.write("<strong>用戶:</strong> " + p.getUsername() + "<br>");
- document.write("<strong>密碼:</strong> " + p.getPassword() + "<br>");
- document.write("<strong>主機:</strong> " + p.getHost() + "<br>");
- document.write("<strong>端口:</strong> " + p.getPort() + "<br>");
- document.write("<strong>路徑:</strong> " + p.getPathname() + "<br>");
- document.write("<strong>查詢字符串:</strong> " + p.getQuerystring() + "<br>");
- document.write("<strong>錨點:</strong> " + p.getFragment() + "<br>");
- </script>
- </div>
- </div>
- </body>
新聞熱點
疑難解答