簡體   English   中英

如何使用正則表達式替換刪除0起始字符?

[英]How do use regular expression replace remove the 0 start character?

我使用此代碼替換非數字字符,但是當數字以0開頭時,例如“ 000001111”或“ 0000000”,則0會出現在前面。

我想替換0開頭的數字,如何解決我的代碼? 當所有輸入均為0時,如“ 00000000”,則僅保留一個0;當輸入編號為“ 000234”時,則保留234。

我的代碼:

<input id="text_target_value" maxlength="11" class="text-right number" type="text" onkeyup="value=value.replace(/[^\d]/g,'')";">

我只想修復onkeyup。

您不需要正則表達式。 就像下面的例子一樣使用Number函數;

 function relpacing($this) { $this.value = Number($this.value); } 
 <input id="text_target_value" maxlength="11" class="text-right number" type="number" onkeyup="relpacing(this)"> 

嘗試在[^\\d]

^0+(?!$)

如果字符串由全零組成,則它將匹配前導零,但不匹配最終零。 另外,最好使用Javascript而不是使用內聯屬性來正確附加處理程序:

 document.querySelector('#text_target_value').onkeyup = function() { this.value = this.value.replace(/[^\\d]+|^0+(?!$)/g, ''); } 
 <input id="text_target_value" maxlength="11" class="text-right number" type="text"> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM