[英]Input field value - remove leading zeros
我在Javascript中有一個文本框。 當我在文本框中輸入'0000.00'
時,我想知道如何將其轉換為只有一個前導零,例如'0.00'
。
更簡化的解決方案如下。 看一下這個!
var resultString = document.getElementById("theTextBoxInQuestion")
.value
.replace(/^[0]+/g,"");
str.replace(/^0+(?!\.|$)/, '')
'0000.00' --> '0.00'
'0.00' --> '0.00'
'00123.0' --> '123.0'
'0' --> '0'
var value= document.getElementById("theTextBoxInQuestion").value;
var number= parseFloat(value).toFixed(2);
聽起來你只想刪除前導零,除非只剩下一個(整數為“0”或浮點數為“0.xxx”,其中x可以是任何東西)。
這對於第一次切割應該是好的:
while (s.charAt(0) == '0') { # Assume we remove all leading zeros
if (s.length == 1) { break }; # But not final one.
if (s.charAt(1) == '.') { break }; # Nor one followed by '.'
s = s.substr(1, s.length-1)
}
好的簡單解決方案。 唯一的問題是,當字符串為“0000.00”時,結果為0。但除此之外,我認為這是一個很酷的解決方案。
var i = "0000.12";
var integer = i*1; //here's is the trick...
console.log(i); //0000.12
console.log(integer);//0.12
在某些情況下,我認為這可行...
您可以使用此代碼:
<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>
試試這個:
<input type="text" onblur="this.value=this.value.replace(/^0+(?=\d\.)/, '')">
您可以使用正則表達式將前導零替換為單個零:
valueString.replace(/^(-)?0+(0\.|\d)/, '$1$2')
>'-000.0050'.replace(/^(-)?0+(0\.|\d)/, '$1$2')
< "-0.0050"
>'-0010050'.replace(/^(-)?0+(0\.|\d)/, '$1$2')
< "-10050"
匹配項: <beginning of text><optional minus sign><any sequence of zeroes><either a zero before the dot or another digit>
替換為: <same sign if available><the part of the string after the sequence of zeroes>
^是文本的開頭
? 表示可選(指前一個字符)
(a | b)表示a或b
。 是點(轉義為。具有特殊含義)
\\ d是任何數字
$ 1表示你在第一組中發現的()
$ 2表示你在第二組中找到的()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.