[英]Remove/ truncate leading zeros by javascript/jquery
建议通过 javascript、jquery 从数字(任何字符串)中删除或截断前导零的解决方案。
您可以在字符串的开头使用与零匹配的正则表达式:
s = s.replace(/^0+/, '');
我会使用Number()函数:
var str = "00001";
str = Number(str).toString();
>> "1"
或者我将我的字符串乘以1
var str = "00000000002346301625363";
str = (str * 1).toString();
>> "2346301625363"
也许有点晚了,但我想加2美分。
如果你的字符串ALWAYS代表一个数字,可能有前导零,你可以使用'+'运算符简单地将字符串转换为数字。
例如
x= "00005";
alert(typeof x); //"string"
alert(x);// "00005"
x = +x ; //or x= +"00005"; //do NOT confuse with x+=x, which will only concatenate the value
alert(typeof x); //number , voila!
alert(x); // 5 (as number)
如果你的字符串不代表一个数字而你只需要删除0就使用其他解决方案,但如果你只需要它们作为数字,这是最短的方法。
如果你将一个空字符串连接到它们,强制数字作为字符串,就像:FYI你可以做相反的事情,例如:
x = 5;
alert(typeof x); //number
x = x+"";
alert(typeof x); //string
希望它能帮到某个人
parseInt(value) or parseFloat(value)
这将很好地工作。
我有这个解决方案在javascript中截断前导零(数字或任何字符串):
<script language="JavaScript" type="text/javascript">
<!--
function trimNumber(s) {
while (s.substr(0,1) == '0' && s.length>1) { s = s.substr(1,9999); }
return s;
}
var s1 = '00123';
var s2 = '000assa';
var s3 = 'assa34300';
var s4 = 'ssa';
var s5 = '121212000';
alert(s1 + '=' + trimNumber(s1));
alert(s2 + '=' + trimNumber(s2));
alert(s3 + '=' + trimNumber(s3));
alert(s4 + '=' + trimNumber(s4));
alert(s5 + '=' + trimNumber(s5));
// end hiding contents -->
</script>
1.<\/strong>最显式的是使用parseInt():
parseInt(number, 10)
试试这个,
function ltrim(str, chars) {
chars = chars || "\\s";
return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
var str =ltrim("01545878","0");
更多这里
您应该使用“parseInt”函数的“radix”参数: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt? redlocale = en-US & redctsctsgg = JavaScript%2FReference %2FGlobal_Objects%2FparseInt
parseInt('015',10)=> 15
如果你不使用它,一些javascript引擎可能会将它用作八进制parseInt('015')=> 0
如果number是int use
"" + parseInt(str)
如果数字是浮动使用
"" + parseFloat(str)
只需尝试乘以一个如下:
“00123”* 1; //获取号码
“00123”* 1 +“”; //获取字符串
来自Guffa<\/a>的正则表达式解决方案,但至少留下一个字符
"123".replace(/^0*(.+)/, '$1'); // 123
"012".replace(/^0*(.+)/, '$1'); // 12
"000".replace(/^0*(.+)/, '$1'); // 0
没有正则表达式的另一种方式:
function trimLeadingZerosSubstr(str) {
var xLastChr = str.length - 1, xChrIdx = 0;
while (str[xChrIdx] === "0" && xChrIdx < xLastChr) {
xChrIdx++;
}
return xChrIdx > 0 ? str.substr(xChrIdx) : str;
}
使用短字符串它会比正则表达式( jsperf )更快
const input = '0093';
const match = input.match(/^(0+)(\d+)$/);
const result = match && match[2] || input;
常量数 = '0000007457841'; console.log(+number) \/\/7457841;
或 number.replace(\/^0+\/, '')
使用“数学.abs”
例如:Math.abs(003) = 3;
console.log(Math.abs(003))
我想删除字符串中每个数字序列的所有前导零,如果数字值等于零,则返回 0。
我最终这样做了:
str = str.replace(/(0{1,}\d+)/, "removeLeadingZeros('$1')")
function removeLeadingZeros(string) {
if (string.length == 1) return string
if (string == 0) return 0
string = string.replace(/^0{1,}/, '');
return string
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.