Reputation: 121
I had regular expression which is onkeyup="this.value=this.value.replace(/[^aA0-9 +]/g,'');
Which is allow string only number with '+' symbol i.e 1+2+3
I had functionality of + for combine. But in some time it allow example '+1' and also '1++3+' or '+++4+5'.
How to prevent repeated '+' and on start with '+' on keyup event so that my functionality will work.
Any suggestion. Thank You.
Upvotes: 1
Views: 203
Reputation: 2575
var element=document.getElementById("txtSum");
element.addEventListener('keyup', function() {
this.value = this.value
.replace(/\s/g, '') // Removes space
.replace(/^\++/g, '') // Remove begining with +
.replace(/[^aA\d +]/g,'')
.replace(/\++/g, '+'); // Replace multiple +
});
<input type="text" id="txtSum"/>
Upvotes: 1
Reputation: 371029
Attach the event listener properly using Javascript, and then you can replace multiple pluses in a row with a single plus by matching \++
(literal plus, repeated) and replacing with +
. Also note that 0-9
in a character set reduces to \d
, which is a bit nicer to read:
element.addEventListener('keyup', function() {
this.value = this.value
.replace(/[^aA\d +]/g,'')
.replace(/\++/g, '+');
});
You might also want to check for spaces around pluses so as to avoid, for example, a+ +a
. If that's the case, then you can use:
.replace(/ *\+[ +]/g, ' + ')
That will replace optional spaces, followed by a plus, followed by any combination of pluses and spaces, with a single plus surrounded by a space on each side. (of course, you could also replace with a plus alone, without spaces, if you wanted)
Upvotes: 1