using Regex in an if else statement

hey guys, I created and logical statement with regex init but doesn't seem to work
let operation = Math.floor((Math.random() * name.length - 1))
if(name[operation] === /\s$/g || name[operation] === undefined) return mathChallenge(name)
let operation = Math.floor((Math.random() * name.length - 1))
if(name[operation] === /\s$/g || name[operation] === undefined) return mathChallenge(name)
so basically on my statement, instead of using " ", I used regex of space. I wonder if using regex is executable and if so, how should it supposed to be
2 Replies
Joao
Joao3y ago
You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match Or build a regexp object and use one of the methods available. It's preferable if you mean to reuse the same regexp over and over: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
13eck
13eck3y ago
You can use regex in an if statement, but what you're doing is checking equality: is name[operation] a regex value? Unless the user is inputting a regex object it won't be true. Like Joao said, you want to see if name[operation] matches the regex you made, so use the String.match() method.
Want results from more Discord servers?
Add your server