Check if a value is numeric in pure JavaScript - isNumeric() function

When working with data in JavaScript, it's important to verify that the values you are working with are of the correct data type. One common check is to determine if a value is numeric. In pure JavaScript, you can create a function called isNumeric() to accomplish this task.


function isNumeric(value) {
  return /^-?d+$/.test(value);
}

The isNumeric() function takes a single argument, value, which is the value you want to check. The function then uses a regular expression to test if the value is numeric.

The regular expression used in isNumeric() checks if the value contains only digits, optionally with a leading negative sign. Here's a breakdown of the regular expression:

  • ^ - Matches the start of the string
  • -? - Matches an optional negative sign
  • d+ - Matches one or more digits
  • $ - Matches the end of the string

If the value matches the regular expression, isNumeric() returns true. Otherwise, it returns false.

Here's an example of using isNumeric() to check if a value is numeric:


console.log(isNumeric(42)); // true
console.log(isNumeric(-42)); // true
console.log(isNumeric("42")); // true
console.log(isNumeric("foo")); // false

By using the isNumeric() function, you can ensure that your JavaScript code is working with numeric values, and avoid errors that can occur when working with incorrect data types.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information