1 回答
TA貢獻1820條經(jīng)驗 獲得超9個贊
不要將所有內(nèi)容都塞入 HTML 事件屬性中。寫一個函數(shù)!
String.fromCharCode(34)這也消除了僅使用雙引號字符的必要性。順便說一句,如果您確實需要在 HTML 屬性中使用雙引號字符,只需使用
".RegExp(/^\d*\.?\d*$/)是重復(fù)的。只需使用/^\d*\.?\d*$/, 因為它已經(jīng)是一個正則表達式。RegExp如果您想將字符串轉(zhuǎn)換為正則表達式,則使用:RegExp("^\\d*\\.?\\d*$").調(diào)用
.exec()并使用它作為參數(shù)是.replace()沒有意義的。.exec()返回一個數(shù)組(包含匹配項),但.replace()需要一個正則表達式(或字符串)作為它的第一個參數(shù)。您還需要將g(lobal) 標(biāo)志添加到表達式中,否則只會替換第一個匹配項this.value?=?this.value.replace(/[A-Za-z-!$%^&*()_+|~=`{}\[\]:;'<>?,\/"]+/g,?'');請注意,我在正則表達式中添加了雙引號字符。但是,僅替換不是數(shù)字或句點的所有內(nèi)容可能會更容易:
this.value?=?this.value.replace(/[^\d.]/g,?'');
不能僅使用正則表達式來刪除額外的句點(至少不是在所有當(dāng)前的瀏覽器中)。一種方法是在句點處處理.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("");?
? }
}
最終結(jié)果(.test不需要??偸莿h除所有無效字符):
function?removeInvalidNumberChars(element)?{
??element.value?=?removeAllButFirstPeriod(element.value.replace(/[^\d.]/g,?''));
}與(input事件是比 更好的選擇keydown)
<input?oninput="removeInvalidNumberChars(this)">
添加回答
舉報
