js 数字日期字符串添加分隔符

方法一:

	const regDate = /^(\d{4})(\d{2})(\d{2})$/;
	console.log(('20220815').replace(regDate, "$1-$2-$3")); //2022-08-15
	
	const regDate2 = /^(\d{2})(\d{2})$/;
	console.log(('0815').replace(regDate2, "$1-$2")); //08-15
	
	const dateTime = '2023-02-09 11:33:59'
	dateTime = dateTime.substring(0, 10).replace(/-/g, '.') // 2023.02.09
	

方法二:

/*
	*  给数字加分隔符
	*  @param number { Number } 传入数字
	*  @param counts { Number } 长度
	*  @param mark { String } 标记 符号
	*/
	function  formatNum(num, counts, mark){
    
    
		num = num.toString().split("."); // 分隔小数点
		var tempAry = num[0].split("").reverse(); // 转换成字符数组并且倒序排列
		var res=[];
		for(var i=0, len=tempAry.length; i<len; i++){
    
    
			if(i%counts===0 && i!==0){
    
    
				res.push(mark); // 添加分隔符
			}
			res.push(tempAry[i]);
		}
		res.reverse(); // 再次倒序成为正确的顺序
		if(num[1]) {
    
     // 如果有小数的话添加小数部分
			res = res.join("").concat("." + num[1]);
		} else {
    
    
			res = res.join("");
		}
		return res;
	}
	// 使用:
	console.log('formatNum----->', this.formatNum('20220815.123', 3, ','));
	
	
	function toThousands2(num, counts, mark) {
    
    
			const result = []
			let counter = 0
			let integer //整数部分
			let decimal //小数部分
			if (Math.ceil(num) !== num) {
    
    
				const numArr = `${
      
      num}`.split('.') //将小数点前后分隔
				integer = numArr[0]
				decimal = numArr[1]
			}
			if (integer) {
    
    
				num = integer
			}
			num = (num || 0).toString().split('')
			for (var i = num.length - 1; i >= 0; i--) {
    
    
				counter++
				result.unshift(num[i])
				if (!(counter % counts) && i !== 0) {
    
    
					result.unshift(mark)
				}
			}
			return result.join('') + (decimal ? `.${
      
      decimal}` : '')
		}
		// 使用:
		console.log('toThousands2----->', this.toThousands2('20220815.123', 3, ','));

猜你喜欢

转载自blog.csdn.net/qq_45565693/article/details/126345527
今日推荐