Home > Web Front-end > JS Tutorial > How Can I Check if a JavaScript String Represents a Valid Number?

How Can I Check if a JavaScript String Represents a Valid Number?

Linda Hamilton
Release: 2024-12-23 02:00:13
Original
787 people have browsed it

How Can I Check if a JavaScript String Represents a Valid Number?

Checking if a String Is a Valid Number

You can verify if a string contains a valid number in JavaScript using the following methods:

1. isNaN() Function

Use isNaN() to check if the variable is not a number, regardless of whether it's a string or a number:

const isNumeric = (str) => !isNaN(str);
console.log(isNumeric('123')); // true
console.log(isNumeric('abc')); // false
Copy after login

2. Numerical Conversion

Convert the string to a number using num:

const num = +str;
console.log(num); // 123 (if str is '123')
console.log(isNaN(num)); // false (if str is '123')
Copy after login

3. parseInt() Function

Extract a number from the beginning of the string using parseInt():

const num = parseInt(str, 10);
console.log(num); // 123 (if str is '123px')
console.log(isNaN(num)); // false (if str is '123px')
Copy after login

4. Notes on Specific Cases

  • Empty strings are interpreted as 0 by num and isNaN(), but as NaN by parseInt().
  • NaN and Infinity are considered numbers by isNaN().
  • parseInt() treats decimals as integers, chopping off any fractional part.
  • " num" converts strings with spaces or other non-numeric characters to 0. parseInt() treats such strings as NaN.

The above is the detailed content of How Can I Check if a JavaScript String Represents a Valid Number?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template