index.js 2.27 KB
/**
 * 页面公共逻辑和接口
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2017/7/5
 */

/**
 * 获取cookie值
 * @param name [string] cookie键名
 * @return [string] cookie值
 */
function cookie(name) {
    var re = new RegExp(name + '=([^;$]*)', 'i'),
        matchPattern = '$1';

    return re.test(decodeURIComponent(document.cookie)) ? RegExp[matchPattern] : '';
}

/**
 * 设置cookie
 * @param name [string] cookie键名
 * @param value [string] cookie值
 * @pamra options [object] cookie参数项
 */
function setCookie(name, value, options) {
    var expires = '',
        path,
        domain,
        secure,
        date;

    if (typeof value !== 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }

        if (options.expires &&
            (typeof options.expires === 'number' || options.expires.toUTCString)) {
            if (typeof options.expires === 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        path = options.path ? '; path=' + options.path : '';
        domain = options.domain ? '; domain=' + options.domain : '';
        secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    }
}

/**
 * query参数解析
 * @return [object] query key-value map
 */
function queryString() {
    var vars = {},
        hash,
        i,
        search = window.location.search,
        hashes = search ? decodeURIComponent(search).slice(1).split('&') : [];

    for (i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars[hash[0]] = hash[1];
    }
    return vars;
}

/**
 * 获取字符串长度(一个中文=2个字符)
 * @param str [string]
 * @return [num] 字符串长度
 */
function getStrLength(str) {
    var cArr = str.match(/[\u4e00-\u9fa5a]/ig);

    return str.length + (cArr === null ? 0 : cArr.length);
}

module.exports = {
    cookie: cookie,
    setCookie: setCookie,
    queryString: queryString,
    getStrLength: getStrLength
};