RogerHN RogerHN - 1 month ago 9
HTML Question

How to complex filter input in javascript?

I wonder if it's possible to filter an input content like this one.

My input accept 16 chars, which have a : separating them into 4 groups:

0123:0055:02AC:01FA


As you can see I separated them in 4 groups because I will use these values later, so I need them separated, but I want to filter the input with the mininum value being
0001:0001:0001:0001
and maximum
0FFF:00FF:0FFF:02FF


I already do a check to see if the input is the valid chars like A-F-09.

It is possible to do that?



$('.entry').keyup(function(e) {
var val = $(this).val().toUpperCase().replace(/[^a-fA-F0-9:]+/,"");
$(this).val(val);
val = $(this).val().split(":").join("");
if (val.length > 0) {
val = val.match(new RegExp('.{1,4}', 'g')).join(":");
}
if (val.length >= 0) {
$('.clearga').show();
}
$(this).val(val);
var galacticCoords = val;
console.log(galacticCoords);
var [A, B, C, D] = galacticCoords.split(":");

if (galacticCoords.length == 19) {
console.log(galacticCoords+" True");
$('.result').html(galacticCoords);
$('.value-a').html(A);
$('.value-b').html(B);
$('.value-c').html(C);
$('.value-d').html(D);
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="entry" placeholder="000F:000F:000F:000F" maxlength="19">

<div class="result"></div>
<div class="block">Value A:<span class="value-a"></span></div>
<div class="block">Value B:<span class="value-b"></span></div>
<div class="block">Value C:<span class="value-c"></span></div>
<div class="block">Value D:<span class="value-d"></span></div>

</body>




Answer Source

if it's what i think it is then it's base 16 numbers, two bytes per each section, which you can do by converting each to an integer and checking it's range.

const range = [2095, 256, 2095, 767];
str.split(':').forEach((val, index) => {
var n = parseInt(val, 16);
   if (n > range[index]){ 
      // .. do something
   }
})

edit: made a function

function filter(str){
    var ranges = [4095, 255, 4095, 767];
    var n;

    return (str.split(':').map((val, index) => {
        n = parseInt(val, 16);
        if (n < 1) return '0001';
        else if (n > ranges[index]) return '0'+ranges[index].toString(16);
        else return val;
    })).join(':')
}