JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text" name="num_field" placeholder="Enter number" value="1453" id="num_field" />
JavaScript
jQuery(document).ready(function() {
$("#num_field").val(digitGroup($("#num_field").val()));
});
$(function() {
$("#num_field").keyup(function() {
var dInput = $(this).val();
var output = digitGroup(dInput);
$(this).val(output);
});
});
function digitGroup(dInput) {
var output = "";
try {
dInput = dInput.replace(/[^0-9]/g, ""); // remove all chars including spaces, except digits.
var totalSize = dInput.length;
for (var i = totalSize - 1; i > -1; i--) {
output = dInput.charAt(i) + output;
var cnt = totalSize - i;
if (cnt % 3 === 0 && i !== 0) {
output = " " + output; // seperator is " "
}
}
} catch (err)
{
output = dInput; // it won't happen, but it's sweet to catch exceptions.
}
return output;
}