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 signd+
- 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.
Leave a Reply
Related posts