Jay Jay - 4 months ago 28
Javascript Question

allow plus(+) sign only once in regular Expression

i am new to regular expression and want to allow plus(+) sign only once in regular Expression. plz explain in simple words if possible



function number(){
var i = document.getElementById("number");
i.value = i.value.replace(/[^0-9]/+/g,"");
}

<input type="text" id="number" onkeyup="number()" />




Answer

Since + is a control character in RegEx, if you want to test for a literal + in your string, you'd have to escape it: \+.

If you just want to replace sequences of multiple plusses with a single plus, you could use this RegEx: /\++/g. The first part, \+, is the literal +. The second part, + is the RegEx control to match against one or more of what is before it. So this RegEx will match against one or more plus signs, and then the following string replace will replace it with just a single plus. (1234++ will become 1234+)

function number(){
  var i = document.getElementById("number");
  i.value = i.value.replace(/\++/g, '+');
}
<input type="text" id="number" onkeyup="number()" />

Edit: If you want to remove all plusses except the first, you could use a function in the second argument of the .replace function, like so:

function number(){
  let first = true;
  var i = document.getElementById("number");
  i.value = i.value.replace(/(\+)+/g, function(match, p1) {
    if(first) {
      first = false;
      return p1;
    }
    else return '';
  });
}
<input type="text" id="number" onkeyup="number()" />