Reputation: 3
How can I write this condition simpler using RegExp?
if (current === '+' || current === '-' || current === '*' || current === '/')
Upvotes: 0
Views: 53
Reputation: 1875
if(/[+*/-]/.test(current)){
//do something
}
Escape these charcters as they have special meaning in regular expression.
Upvotes: 0
Reputation: 225074
if current
is always one character,
regex
if (/[+*/-]/.test(current))
ES6, no regex
if ('+*/-'.contains(current))
non-ES6, no regex
if ('+*/-'.indexOf(current) !== -1)
non-ES6, no regex, short
if (~'+*/-'.indexOf(current))
if not,
regex
if (/^[+*/-]$/.test(current))
ES6, no regex
if ([...'+*/-'].contains(current))
non-ES6, no regex
if (['+', '*', '/', '-'].indexOf(current) !== -1)
Upvotes: 6
Reputation: 1075019
You use a character class and the test
function of regular expressions:
if (/^[-+*/]$/.test(current)) {
// ...
}
Note the ^
and $
assertions (beginning and end of input), so that "-+"
won't match.
Example:
var rex = /^[-+*/]$/;
["p", "+", "-", "-+"].forEach(function(current) {
console.log(current, rex.test(current));
});
Upvotes: 0