我正在尝试替换错误的输入表单输入字段。有什么方法可以让这段代码工作吗?
<span class="input-bet">
<input type="text" placeholder="0" data-required="true" maxlength='6'/>
</span>
$('.input-bet > input').on('input propertychange paste', function(e) {
var youreg = /^[ю]+/gi;
for (var i = 0;i<this.value.length;i++){
if(this.value[i].match(youreg)){
this.value[i] = this.value[i].replace(youreg, '.');
}
}
如果有人需要 - 这是可行的解决方案 fiddle
最佳答案
您不能分配给文本输入元素值中的单个字符。不过,您可以替换该值。您的脚本可以更改为:
$('.input-bet > input').on('input propertychange paste', function(e) {
var youreg = /ю/gi;
for (var i=0; i<this.value.length; i++){
if (this.value[i].match(youreg)) {
this.value = this.value.replace(youreg, '.');
}
}});
但这效率很低,因为它对每个字符执行正则表达式匹配
。相反,您可以使用 replace()
一次性替换有问题的字符:
$('.input-bet > input').on('input propertychange paste', function(e) {
this.value = this.value.replace(/ю/ig, '.');
});
请注意,如果您仅匹配单个字符,则模式中的 []
不是必需的。如果您想匹配和替换多个字符,则可以使用此模式:
this.value = this.value.replace(/[a-zю]/ig, '.');
例如,它将替换从“a”到“z”以及“ю”的所有字符。
关于javascript - 替换输入字段中的错误输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38257238/