Adding the symbols \+?\-?
into the character class allows for the presence of +
, -
, or ?
within the string.
If you want to permit a +
or -
at the beginning and end of the string, use
/^[-+]?\d+[-+]?$/
^^^^^ ^^^^^
The [-+]?
matches either +
or -
occurring zero or one time (due to the ?
quantifier).
Alternatively, if the signs are only allowed at the start OR only at the end, utilize
/^([-+]?\d+|\d+[-+]?)$/
Explanation of the pattern:
^
- denotes the start of the string
(
- Group initiation
[-+]?
- represents 1 or 0 instances of -
or +
\d+
- signifies 1 or more digits
|
- or
\d+
- indicates 1 or more digits
[-+]?
- stands for 1 or 0 occurrences of -
or +
)
- marks the conclusion of the group
$
- specifies the end of the string.
Furthermore, it's recommended to employ RegExp#test
for checking if a string adheres to a specific pattern rather than using String#match
:
var NumberplusminusRegex =/^[-+]?\d+[-+]?/;
if (NumberplusminusRegex.test(charTyped)) { // Returns yes or no
function btnNumber(){
charTyped=document.getElementById('txtNumber').value;
var NumberplusminusRegex =/^[-+]?\d+[-+]?/; // REMINDER: Avoid using /g with RegExp.test()
if (NumberplusminusRegex.test(charTyped)) { // Check for match
alert('yeah');
return true;
}
else {
alert('whoa');
return false;
}
}
<button onclick="btnNumber()">Click me</button>
<input type='text' id='txtNumber'/>