Tags
Asked 2 years ago
16 Jun 2021
Views 176
Ed

Ed posted

how to check if a string is a valid number in JavaScript

how to check if a string is a valid number in JavaScript
jaggy

jaggy
answered Apr 27 '23 00:00

To check if a string is a valid number in JavaScript, you can use the is NaN() function or the Number() constructor.

Using isNaN(): The isNaN() function returns true if the argument is not a number, and false if it is a number. However, it can be a bit tricky to use because it also returns true for some non-numeric values, such as NaN , Infinity , and - Infinity . Here's an example:



const str1 = "123";
const str2 = "abc";

console.log(isNaN(str1)); // Output: false
console.log(isNaN(str2)); // Output: true

Using the Number () constructor: The Number () constructor returns NaN if the argument is not a valid number. However, it can also be a bit tricky to use because it coerces non-numeric values to numbers in some cases, such as when they contain leading or trailing whitespace. Here's an example:



const str1 = "123";
const str2 = "abc";

console.log(Number(str1)); // Output: 123
console.log(Number(str2)); // Output: NaN

To check for a valid number, you can combine both methods by checking if the string is not NaN and is not an empty string like this:


function isNumeric(str) {
  return !isNaN(str) && str.trim() !== '';
}

console.log(isNumeric("123")); // Output: true
console.log(isNumeric("abc")); // Output: false
console.log(isNumeric("")); // Output: false
console.log(isNumeric("   ")); // Output: false

In this example, isNumeric () returns true if the input is a valid number and is not an empty string. Note that we use str.trim() to remove any leading or trailing whitespace from the string before checking if it is not empty.
Post Answer