Home > Web Front-end > JS Tutorial > How to determine whether a string is a number in javascript

How to determine whether a string is a number in javascript

青灯夜游
Release: 2022-02-16 14:17:20
Original
21366 people have browsed it

In JavaScript, you can use the Number() function and isNaN() function to determine whether a string is a number. The syntax is "isNaN(Number("String",10)"; if true is returned, then the The string is not a number, otherwise it is a number.

How to determine whether a string is a number in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

javascript determines whether a string is a number

In the process of converting a string into a number through Number(), if the string contains non-numbers, then Will return NaN, refer to the following code

Number("Hello",10);//return NAN  
Number("110",10);//return 110 
Number("t2110",10);//return NAN  
Number("1f10g",10);//return NAN
Copy after login

How to determine whether a string is a number in javascript

So you can use isNaN() to determine whether the return value of Number() is NaN to determine whether the string is a number. If it returns true, the string is not a number, otherwise it is a number.

Implementation code:

function f(a){
	if(isNaN(Number(a,10))){
		console.log("不是数字");
	}
	else{
		console.log("是数字");
	}
}
Copy after login

Test:

f("hello");
f("10");
f("d10jh5");
f("10jh5");
Copy after login

How to determine whether a string is a number in javascript

Note: You cannot use the following method to judge:

Number("Hello",10)==NaN;//return false  
Number("110",10)==NaN;//return false
Copy after login

Because NaN and itself do not want to wait, this is quite special. The way to judge NaN is isNaN().

[Related recommendations: javascript learning tutorial

The above is the detailed content of How to determine whether a string is a number in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template