JSFiddle - React, Tailwind, and code Playground
HTML
<input class="numberControl" value="Hey 180! (-1): are {0|-5|9) - (0|0|0)" />
JavaScript
function createSelection(field, start, end) {
if (field.createTextRange) {
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end);
selRange.select();
} else if (field.setSelectionRange) {
field.setSelectionRange(start, end);
} else if (field.selectionStart) {
field.selectionStart = start;
field.selectionEnd = end;
}
}
$("input.numberControl").on("keydown", function (e) {
var gotCode = false;
var curPos = this.selectionStart;
var endPos = this.selectionEnd;
if (endPos === curPos) endPos = curPos + 1;
// get the selected text
var cur = $(this).val().substring(curPos, endPos);
//check for negative numbers or comma
if (cur == '-' || cur == '.') {
endPos++;
cur = $(this).val().substring(curPos, endPos);
}
// we are not at a number - ignore
if (isNaN(cur) || cur.charAt(0) === ' ') {
// search the "other" way
endPos = curPos;
curPos = curPos - 1;
cur = $(this).val().substring(curPos, endPos);
}
if (isNaN(cur) || cur.charAt(0) === ' ' || cur === '') {
return;
}
// check the chars before and after to get the "whole" number
var start = curPos,
end = endPos;
while (start >= 0) {
cur = $(this).val().substring(start, endPos);
// found a cur that is "not" a number
if (cur !== '-' && (isNaN(cur) || cur.charAt(0) === ' ')) {
start++;
break;
}
start--;
}
while (end <= $(this).val().length) {
cur = $(this).val().substring(curPos, end);
// found a cur that is "not" a number
if (isNaN(cur) ||...