javascriptregexp-replace

Using RegExp to get just one "-" at the start if needed


I want a number, a minimum of -1, and only a negative being inputed at the start.

This is what I have so far. The -1 minimum does not work. The single decimal point works great. The single negative sign works great. BUT I cannot force the negative to only appear at the start.

How can I get the negative only at the start if required? How can I get the minimum of -1 working?

<input type="text" id="mynumber" min="-1"
        oninput="this.value = this.value.replace(/[^0-9.-]/g, '').replace(/(\..*)\./g, '$1').replace(/(\--*)\-/g, '$1');" /> 


Solution

  • You could use 1 pattern for the first 2 calls to replace:

    [^0-9.\n-]+|^-(?:1\.0*[1-9]|[2-9]|1\d+).*|(?!^)-
    

    The pattern matches:

    See a regex demo.

    Keep the last call to remove the second occurrence of the dot.

    function handleInput() {
      this.value = this.value.replace(/[^0-9.\n-]+|^-0*(?:1\.0*[1-9]|[2-9]|1\d+).*|(?!^)-/g, '').replace(/(\..*)\./g, '$1');
    }
    
    const inp = document.getElementById("mynumber");
    
    if (inp) {
      inp.addEventListener("input", handleInput);
    }
    <input type="text" id="mynumber" />

    If a lookbehind assertion is supported in your JavaScript environment, you can use a single replace:

    function handleInput() {
      this.value = this.value.replace(/[^0-9.\n-]+|^-0*(?:1\.0*[1-9]|[2-9]|1\d+).*|(?!^)-|(?<!^[^\n.]*)\./g, '');
    }
    
    const inp = document.getElementById("mynumber");
    
    if (inp) {
      inp.addEventListener("input", handleInput);
    }
    <input type="text" id="mynumber" />