继续Mootools常用方法扩展,依然还是String类的扩展。

方法:unescapseHTML

说明:这个上次忘了,和escapseHTML正好是一对儿,功能正好相反。

String.implement({
    unescapseHTML: function() {
        ///<summary>
        /// 反转义字符中的HTML代码
        ///</summary>
        ///<returns type="STRING" />
        var htmlChars = ['&~&amp;', '<~&lt;', '>~&gt;'];
        var r;
        var s = this;
        for (var i = htmlChars.length - 1; i >= 0; i--) {
            r = htmlChars[i].split('~');
            s = s.replace(new RegExp(r[1], 'g'), r[0]);
        }
        return s;
    }
}

简单示例:

var s = '<a b&c=d>'.escapseHTML();
alert(s);
// 将显示:<a b&c=d>
alert(s.unescapseHTML());

方法:toHash

说明:把查询字符串转成Hash对象,注意:一定要是查询字符串哦!比如字符串”a=b&c=2″。

String.implement({
    toHash: function(decode) {
        ///<summary>
        /// 把查询字符串(必须是查询字符串)转化为Hash对象
        /// 返回包含参数的hash对象
        ///</summary>
        ///<param name="decode" type="Boolean">是否要对字符串进行decode</param>
        ///<returns type="Hash" />
        decode = decode ? true : false;
        var ret = new Hash();
        var pairs = this.split('&');
        var pair = '';
        var tmp = [];
        for (var i = 0, ilen = pairs.length; i < ilen; i++) {
            pair = pairs[i];
            tmp = pair.split('=');
            if (tmp.length != 2) continue;
            if (decode) {
                ret.include(decodeURIComponent(tmp[0]), decodeURIComponent(tmp[1]));
            }
            else {
                ret.include(tmp[0], tmp[1]);
            }
        }
        return ret;
    }
}

简单示例:

// 将显示:2
alert('a=b&c=2&d=ef'.toHash().get('c'));

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.