Bogdan Tushevskyi Bogdan Tushevskyi - 5 months ago 25
Javascript Question

replace wrong input from input field

I'm trying to replace wrong input form input field. Is this any way to made this code work?

<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, '.');
}
}


if someone need - here is working solution
fiddle

Answer

You can't assign to individual characters in the text input element's value. You can, however, replace the value. Your script can be changed to this:

$('.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, '.');
     }
 }});

But this is inefficient because it performs a regex match for every character. Instead you can replace the offending characters in one go using replace():

$('.input-bet > input').on('input propertychange paste', function(e) {
    this.value = this.value.replace(/ю/ig, '.');
});

Note that the [] in your pattern is not required if you are matching just a single character. If you want to match and replace multiple characters then you can use this pattern:

this.value = this.value.replace(/[a-zю]/ig, '.');

which for example will replace all characters from 'a' to 'z' as well as 'ю'.