0

I have a discord bot and I'm trying to figure out a way of knowing if a message is a number. Here's the code I have:

if (message.isNumber()){
   //do something
}
String.prototype.isNumber = function() {
  return /^\d+$/.test(this);
};

When I test it, it does absolutely nothing. Can someone help me out?

Baneina
  • 9
  • 2
  • Hi welcome to SO ! I think the prototype you added to `String` would only work if the variable is ... a `String`. Checkout my answer to see what other options you have ! – turbopasi Jan 05 '21 at 18:40

2 Answers2

0

You could simply do:

if(isNaN(message.content) return;
else {
  //do something
}

If the message is not a number, it would do nothing. Otherwise it would do that what you would like it to do.

Jannik Schmidtke
  • 1,257
  • 2
  • 5
  • 15
0

Since OP does not provide more context about what message is, I assume message already holds the value that needs to be checked. So I also have to ignore that message could be an object coming from Discord.js, and that the value OP wants to check really is located at message.content, not message. Even if I know Discord.js API, message could be something completely different here.

If the value that needs to be checked really is located at message.content and does come from Discord.js API, checkout @JannikSchmidtke answer, he might know more about the Discord.js API and the context about this question.


Case A : You want to check if the type of a variable is a number

You can use typeof to check the type of it :

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

if (typeof message == 'number') { console.log('is a number'); }
if (!(typeof message == 'number')) { console.log('is a not a number'); }

Case B : You want to check a variable if it is a valid number

You could use isNaN in certain cases. Here a string could be a valid number as well:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN

isNaN(123)         // false, it is a number
isNaN('123')       // false, it is a number
isNaN('1e10000')   // false (This translates to Infinity, which is a number)
isNaN('foo')       // true, it is not a number
isNaN('10px')      // true, is is not a number

You will also find a very good and complete answere here : (Built-in) way in JavaScript to check if a string is a valid number

turbopasi
  • 3,327
  • 2
  • 16
  • 43
  • To whom suggested an edit to my answer : OP does not include what `message` actually is so I have to assume `message` is the actual content that needs to be checked. If `message` is an object it will fail because an object is not a number , simple as that. – turbopasi Jan 05 '21 at 18:47