1 回答

TA貢獻1820條經驗 獲得超9個贊
不要將所有內容都塞入 HTML 事件屬性中。寫一個函數!
String.fromCharCode(34)
這也消除了僅使用雙引號字符的必要性。順便說一句,如果您確實需要在 HTML 屬性中使用雙引號字符,只需使用
"
.RegExp(/^\d*\.?\d*$/)
是重復的。只需使用/^\d*\.?\d*$/
, 因為它已經是一個正則表達式。RegExp
如果您想將字符串轉換為正則表達式,則使用:RegExp("^\\d*\\.?\\d*$")
.調用
.exec()
并使用它作為參數是.replace()
沒有意義的。.exec()
返回一個數組(包含匹配項),但.replace()
需要一個正則表達式(或字符串)作為它的第一個參數。您還需要將g
(lobal) 標志添加到表達式中,否則只會替換第一個匹配項this.value?=?this.value.replace(/[A-Za-z-!$%^&*()_+|~=`{}\[\]:;'<>?,\/"]+/g,?'');
請注意,我在正則表達式中添加了雙引號字符。但是,僅替換不是數字或句點的所有內容可能會更容易:
this.value?=?this.value.replace(/[^\d.]/g,?'');
不能僅使用正則表達式來刪除額外的句點(至少不是在所有當前的瀏覽器中)。一種方法是在句點處處理.split
字符串,然后將其與第一項和第二項之間的句點連接起來:
function removeAllButFirstPeriod(string) {
? const split = string.split(".");
? if (split.length === 1) {
? ? // If the split string contains only one element, then there were no periods in the string
? ? return split[0];
? } else {
? ? return split[0] + "." + split.slice(1).join("");?
? }
}
最終結果(.test
不需要??偸莿h除所有無效字符):
function?removeInvalidNumberChars(element)?{ ??element.value?=?removeAllButFirstPeriod(element.value.replace(/[^\d.]/g,?'')); }
與(input
事件是比 更好的選擇keydown
)
<input?oninput="removeInvalidNumberChars(this)">
添加回答
舉報