Home > Software engineering >  use replace to remove chars not existing in a regex match
use replace to remove chars not existing in a regex match

Time:04-08

I'am trying to allow following pattern for a single html input box with javascript regex

  • -int (aka any minus number so long it not followed by a zero and is in the first position)
  • 0 (a single zero is allowed)
  • int (is allowed)

I use this function the remove anything that doesn't match it

    $('.dointcheck').live('keyup',
        function () {
            $(this).val($(this).val().replace((/^((?!:([1-9-]?[0-9])).)/g), ''));
            if ($(this).val().length == 0) {
                $(this).val(0);
            }
        }); 

which doesn't work. Other examples is:

  1. /[^-0-9]/g it removes any non valid chars but doesnt check if the minus is the beginning and is followed by a zero. It allows minus everywhere in the string
  2. (/^((?!:([1-9-]?[0-9])).)/g Don't allow none.
  3. [^1-9-]?[^0-9]* Allow all...

I think I'am missing something.. Any suggestions would be most appreciated..

CodePudding user response:

I changed your regexp and made it a bit more modular and it worked fine.

function toValidNumber(int) {
  return (/^\s*[ -]?(\d |\d*\.\d |\d \.\d*)([Ee][ -]?\d )?\s*$/).test(int) ? int : 0;
}

$('.dointcheck').live('keyup',
  function () {
    $(this).val(toValidNumber($(this).val()));
  }); 

Orginal RegEXP in Stackoverflow

CodePudding user response:

You may try this regex

^(0).*|^(-?)([1-9]\d*)?.*|^.*

and replace it with $1$2$3 after input

document.querySelector('input').addEventListener('input', ({ target }) => target.value = target.value.replace(/^(0).*|^(-)?([1-9]\d*)?.*|^.*/g, '$1$2$3'));
<input />

It has three tests:

^(0).*               // if it starts with 0, discard everything after it
^(-)?([1-9]\d*)?.*   // otherwise it can only starts with a -, or any number that is not a 0. Then followed by other digits, then discard everything after it
^.*                  // if previous rules are not matched, discard everything

In short:

  • generally only -, 0-9 are allowed.
  • if you type a 0 first, nothing will be allowed after.
  • if you type a 1-9 first, only numbers are allowed after.
  • if you type a - first, only 1-9 is allowed next, then any digit is allowed after.
  • Related