js 操作(数字前端去0、文字去除空格、截取字符串、保留几位小数、数字不足位数前补0)
1、数字前端去0
var num = number.replace(/\b(0+)/gi,"")
2、文字去除空格
var str = str.replace(/(^\s*)|(\s*$)/g, "")
3、截取字符串
var str = abcdef str = str.substr(2,3) //cde
4、保留小数
//保留4位小数 var number = 12.3321432; number = String(number).replace(/^(.*\..{4}).*$/,"$1"); number = Number(number); // number = 12.3321 //保留2位小数 var reg = /^(.*\..{2}).*$/; var number2 = 12.3; number2 = String(number2).replace(reg ,"$1"); number2 = Number(number2); // number2 = 12.3 不足保留位数不补0
5、数字不足位数前补0
var number = 100 var num = (Array(5).join(0) +number).slice(-5) //num = 00100