вторник, 10 марта 2015 г.
URL Parsing with JavaScript
Server-side URL Parsing
// Server-side JavaScript
var urlapi = require('url'),
url = urlapi.parse('http://site.com:81/path/page?a=1&b=2#hash');
console.log(
url.href + '\n' + // the full URL
url.protocol + '\n' + // http:
url.hostname + '\n' + // site.com
url.port + '\n' + // 81
url.pathname + '\n' + // /path/page
url.search + '\n' + // ?a=1&b=2
url.hash // #hash
);
Client-side URL Parsing
// Client-side JavaScript
// find the first link in the DOM
var url = document.getElementsByTagName('a')[0];
console.log(
url.href + '\n' + // the full URL
url.protocol + '\n' + // http:
url.hostname + '\n' + // site.com
url.port + '\n' + // 81
url.pathname + '\n' + // /path/page
url.search + '\n' + // ?a=1&b=2
url.hash // #hash
);
If we have a URL string, we can use it on an in-memory anchor element (a) so it can be parsed without regular expressions, e.g.:
// Client-side JavaScript
// create dummy link
var url = document.createElement('a');
url.href = 'http://site.com:81/path/page?a=1&b=2#hash';
console.log(url.hostname); // site.com
Isomorphic URL Parsing
// lib.js library functions
// running on Node.js?
var isNode = (typeof module === 'object' && module.exports);
// alternative check of running on Node.js?
// var isNode = typeof window === 'undefined';
(function(lib) {
"use strict";
// require Node URL API
var url = (isNode ? require('url') : null);
// parse URL
lib.URLparse = function(str) {
if (isNode) {
return url.parse(str);
}
else {
url = document.createElement('a');
url.href = str;
return url;
}
}
})(isNode ? module.exports : this.lib = {});
Server-side, URLparse is exported as a Common.JS module. To use it:
// include lib.js module
var lib = require('./lib.js');
var url = lib.URLparse('http://site.com:81/path/page?a=1&b=2#hash');
console.log(
url.href + '\n' + // the full URL
url.protocol + '\n' + // http:
url.hostname + '\n' + // site.com
url.port + '\n' + // 81
url.pathname + '\n' + // /path/page
url.search + '\n' + // ?a=1&b=2
url.hash // #hash
);
Client-side, URLparse is added as a method to the global lib object:
<script src="./lib.js"></script>
<script>
var url = lib.URLparse('http://site.com:81/path/page?a=1&b=2#hash');
console.log(
url.href + '\n' + // the full URL
url.protocol + '\n' + // http:
url.hostname + '\n' + // site.com
url.port + '\n' + // 81
url.pathname + '\n' + // /path/page
url.search + '\n' + // ?a=1&b=2
url.hash // #hash
);
</script>
Подписаться на:
Комментарии к сообщению (Atom)
Комментариев нет:
Отправить комментарий