javascript 常用字符串处理

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 常用字符串处理相关的知识,希望对你有一定的参考价值。

export function formatTime(date,format){
	return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a){
            switch (a) {
                case 'yyyy':
                    return date.substr(0,4);
                case 'MM':
                    return date.substr(4,2);
                case 'dd':
                    return date.substr(6,2);
				case 'mm':
                    return date.substr(8,2);
				case 'ss':
                    return date.substr(10,2);
            }
        })
};

export function formatTimeString(date,format){
    // 处理Safari 兼容
    if(typeof date === 'string' && date.indexOf('-')>-1){
        date = date.replace(/-/g,'/')
    }
	let time = new Date(date);
	return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a){
            switch (a) {
                case 'yyyy':
                    return time.getFullYear();
                case 'MM':
                    return (time.getMonth()+1) < 10 ? '0'+(time.getMonth()+1) :(time.getMonth()+1);
                case 'dd':
                    return time.getDate() < 10 ? '0'+time.getDate() :time.getDate();
				case 'HH':
                    return time.getHours() < 10 ? '0'+time.getHours() :time.getHours();
				case 'mm':
                    return time.getMinutes() < 10 ? '0'+time.getMinutes() :time.getMinutes();
				case 'ss':
                    return time.getSeconds() < 10 ? '0'+time.getSeconds() :time.getSeconds();
            }
        })
};



function getDatStartEnd(date) {
    var Start = new Date(date.getFullYear() + '-' + ((date.getMonth() + 1) < 10 ? ('0' + (date.getMonth() + 1)) : (date.getMonth() + 1)) + '-' + (date.getDate() < 10 ? ('0' + date.getDate()) : date.getDate()) + ' 00:00:00').getTime();
    var End = new Date(date.getFullYear() + '-' + ((date.getMonth() + 1) < 10 ? ('0' + (date.getMonth() + 1)) : (date.getMonth() + 1)) + '-' + (date.getDate() < 10 ? ('0' + date.getDate()) : date.getDate()) + ' 23:59:59').getTime();
    return { Start, End };
}
function GetDateStr(AddDayCount, current) {
    var dd = current || new Date();
    dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1; //获取当前月份的日期
    var d = dd.getDate();
    return y + "-" + m + "-" + d;
}

// - 1分钟内:刚刚
// - 1小时内:X分钟前
// - 24小时内:X小时前
// - 24小时外:昨天
// - 昨天0点以前:前天
// - 30天内:X天前
// - 30天前:YYYY-MM-DD
export function formateTime(dateTime) {
    var result = '';
    var nowTime = new Date().getFullYear() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getDate() + ' ' + new Date().getHours() + ':' + new Date().getMinutes() + ':00';
    nowTime = new Date(nowTime).getTime();
    var today = getDatStartEnd(new Date());
    var pre = getDatStartEnd(new Date(GetDateStr(-1)));
    var prePre = getDatStartEnd(new Date(GetDateStr(-2)));
    var prePreTen = getDatStartEnd(new Date(GetDateStr(-29)));
    var temp = new Date(dateTime).getTime();
    if (nowTime < temp) {
        result = '刚刚';
        return result;
    }
    if (((nowTime - temp) / (1000 * 60)) < (60)) {
        result = Math.ceil((nowTime - temp) / (1000 * 60)) + '分钟前';
        return result;
    }
    if (((nowTime - temp) / (1000 * 60 * 60)) < 24) {
        result = Math.ceil((nowTime - temp) / (1000 * 60 * 60)) + '小时前';
        return result;
    }
    if (pre.Start < temp && temp < pre.End) {
        result = '昨天';
        return result;
    }
    if (prePre.Start < temp && temp < prePre.End) {
        result = '前天';
        return result;
    }
    if (prePreTen.Start < temp) {
        var days = Math.ceil((new Date().getTime()-new Date(dateTime).getTime())/(60*60*1000*24));
        result = days + '天前';
        return result;
    }
    return dateTime.substr(0, 11);
}
// 今天24点前:今天
// 明天0点~24点:明天
// else:X天后
// 24小时外:昨天
// 昨天0点以前:前天
// 30天内:X天前
// 30天前:YYYY-MM-DD
function getDatStartEnd2(date) {
	var Start = new Date(date.getFullYear() + '/' + ((date.getMonth() + 1) < 10 ? ('0' + (date.getMonth() + 1)) : (date.getMonth() + 1)) + '/' + (date.getDate() < 10 ? ('0' + date.getDate()) : date.getDate()) + ' 00:00:00').getTime();
	var End = new Date(date.getFullYear() + '/' + ((date.getMonth() + 1) < 10 ? ('0' + (date.getMonth() + 1)) : (date.getMonth() + 1)) + '/' + (date.getDate() < 10 ? ('0' + date.getDate()) : date.getDate()) + ' 23:59:59').getTime();
	return { Start, End };
}
function GetDateStr2(AddDayCount, current) {
	var dd = current || new Date();
	dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期
	var y = dd.getFullYear();
	var m = dd.getMonth() + 1; //获取当前月份的日期
	var d = dd.getDate();
	return y + "/" + m + "/" + d;
}
export function formatewithAfterTime(dateTime) {
	var result = '';
	if(typeof dateTime === 'string' && dateTime.indexOf('-')>-1){
		dateTime = dateTime.replace(/-/g,'/')
	}
	var nowTime = new Date().getFullYear() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getDate(  ) + ' ' + new Date().getHours() + ':' + new Date().getMinutes() + ':00';
	nowTime = new Date(nowTime).getTime();
	var today = getDatStartEnd2(new Date());
	var next = getDatStartEnd2(new Date(GetDateStr2(+1)));
	var pre = getDatStartEnd2(new Date(GetDateStr2(-1)));
	var prePre = getDatStartEnd2(new Date(GetDateStr2(-2)));
	var prePreTen = getDatStartEnd2(new Date(GetDateStr2(-29)));
	var temp = new Date(dateTime).getTime();
	if ((nowTime - temp)<(1000 * 60)) {
		result = '刚刚';
		return result;
	}
	if (today.Start <= temp && temp <= today.End) {
		result = '今天';
		return result;
	}
	if (next.Start <= temp && temp <= next.End) {
		result = '明天';
		return result;
	}
	if (pre.Start <= temp && temp <= pre.End) {
		result = '昨天';
		return result;
	}
	if (prePre.Start <= temp && temp <= prePre.End) {
		result = '前天';
		return result;
	}
	if (temp > next.End ) {
		var days = Math.ceil((new Date(dateTime).getTime()-new Date().getTime())/(60*60*1000*24));
		result = days+'天后';
		return result;
	}
	if (prePreTen.Start < temp) {
		var days = Math.ceil((new Date().getTime()-new Date(dateTime).getTime())/(60*60*1000*24));
		result = days + '天前';
		return result;
	}
	return dateTime.substr(0, 11);
}



/**
 *  str 为2015-06-04
 *  格式化  2015年06月04日
 */
export function formatTimeToCN(str,format) {
    str =typeof str ==='string' &&  str.indexOf('-')>-1 ? str.replace(/[-]/g,'/'): str;
	let time = new Date(str);
	if(time){
		return format.replace(/yyyy|MM|dd/g, function (a){
			switch (a) {
			case 'yyyy':
				return time.getFullYear()+'年';
			case 'MM':
				return ((time.getMonth()+1) < 10 ? '0'+(time.getMonth()+1) :(time.getMonth()+1)) +'月';
			case 'dd':
				return (time.getDate() <10 ? '0'+time.getDate() : time.getDate())+'日';
			}
		})
	}
}


/**
 * 拼接URL 参数
 * key=xxxx&key2=xxxxx
 * params={
 *     a:'xxx',
 *     b:'xxx'
 * }
 */

export function getURLParmas(params){
	let a = [],i=0;
	for (var k in params) {
		k ? a[i++] = k + '=' + params[k] : '';
	}
	return a.join('&')
}

export function Serialize ( a ) {
    ///    <summary>
    ///        This method is internal.  Use serialize() instead.
    ///    </summary>
    ///    <param name="a" type="Map">A map of key/value pairs to serialize into a string.</param>'
    ///    <returns type="String" />
    ///    <private />

    var s = [ ];

    function add( key, value ){
        s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
        //s[ s.length ] = (key) + '=' + (value);
    };

    // Serialize the key/values
    for ( var j in a ){
        add( j, a[j] );
    }

    // Return the resulting serialization
    return s.join("&").replace(/%20/g, "+");
}

/**
 * 字符串数字千位加上,分割
 * @param str
 * @param len
 * @returns {*}
 */
export function formateNumberToDot (str) {
    if(!str){
        return '';
    }
    var temp = Number(str);
    if (isNaN(temp))
    {
        return str;
    }
    str += '';
    var floatStr = str.substr(str.indexOf('.'));
    var strPre =  str.substr(0,str.indexOf('.'));
    strPre = strPre.split('').reverse();
    var dobNum = Math.floor(strPre.length/3)+(strPre.length%3==0?-1:0);
    for(var i = 0,len = dobNum;i<len;i++){
        strPre.splice(((i+1)*3+i),0,',');
    }
    return strPre.reverse().join('')+floatStr;
}

/**
 * 自动加...  汉字当成两个算
 * @param str
 * @param len
 * @returns {*}
 */
export function spliceStringByLength (str, len, hasNoDotted) {
    var strlen = 0;
    var s = "";
    if(!str){
        return '';
    }
    for (var i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) > 128) {
            strlen += 2;
        } else {
            strlen++;
        }
        s += str.charAt(i);
        if (strlen >= len) {
            if (i == (str.length - 1)) {
                return s;
            }
            return s +(hasNoDotted?'':'...');
        }
    }
    return s;
}
/**
 * 图片url判断
 */
export function imgUrl(url) {
    if(url){
        if(url.substr(0,2) == "i/"){
            return 'https://yun.lagou.com'+"/"+url;
        }else{
            return 'https://yun.lagou.com'+url;
        }
    }else{
        return "";
    }
}
/**
 * 根据姓名切割返回名字
 * sdfa中  => 中
 */
export function splitName (name,len) {
    var len = len || 2
    if(!name) return '';
    var reg = /[\u4E00-\u9FA5\uF900-\uFA2D]+/g;
    name=name+'';
    var rs = name.match(reg);
    if(rs && rs.length>0){
        var result = rs[rs.length-1];
        return result.substr(((result.length-len)<0?0:(result.length-len)),len||2);
    }else{
        return name.substr(0,2);
    }
}

以上是关于javascript 常用字符串处理的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript里处理字符串的一些常用方法

JavaScript常用的数据类型的处理方式

JavaScript进阶之常用字符串方法总结

javascript中字符串对象常用的方法和属性

javascript数据相关处理,序列化反序列化,数据编码与解码

JavaScript 数据处理 - 映射表篇