此类技巧还有很多,欢迎继续分享
解析 URL
从 James Padolsey 的 Blog 中看到的个小技巧,就是利用 a 标签的 DOM 属性解析 URL 字符串。
// 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(/tp:\/\/[^\/]+(.+)/) || [,''])[1],
segments: a.pathname.replace(/^\//,'').split('/')
};
}
可对比下「传统的」正则解析方式( 取自 Tbra 库 ),至少上面代码看起来更容易理解得多
parseURL: (function() {
var keys = ['source',
'prePath',
'scheme',
'username',
'password',
'host',
'port',
'path',
'dir',
'file',
'query',
'fragment'];
var re = /^((?:([^:\/?#.]+):)?(?:\/\/)?(?:([^:@]*):?([^:@]*)?@)?([^:\/?#]*)(?::(\d*))?) \
((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*)) \
(?:\?([^#]*))?(?:#(.*))?/;
return function(sourceUri) {
var uri = {};
var uriParts = re.exec(sourceUri);
for(var i = 0; i < uriParts.length; ++i) {
uri[keys[i]] = (uriParts[i] ? uriParts[i] : '');
}
return uri;
}
})();
(反)转义 HTML
取自 Prototype 中的相应代码
escapeHTML: function(str) {
var div = document.createElement('div');
var text = document.createTextNode(str);
div.appendChild(text);
return div.innerHTML;
}
unescapeHTML: function(str) {
var div = document.createElement('div');
div.innerHTML = str.replace(/<\/?[^>]+>/gi, '');
return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
}
-- EOF --