variable take numbers only and check it using javascript
- User
variable take numbers only and check it using javascript
- Assistant
You can use the
isNaN()function in JavaScript to check if a variable contains only numbers. Here is an example:javascriptlet num = 123; if (!isNaN(num)) { console.log("Variable contains only numbers"); } else { console.log("Variable contains characters other than numbers"); }If
numcontains only numbers, it will output "Variable contains only numbers". Ifnumcontains characters other than numbers, it will output "Variable contains characters other than numbers". - User
no i want use regex as ^[0-9]*$
- Assistant
Sure, you can use a regular expression to check if a variable contains only numbers. Here is an example using the regular expression
^[0-9]*$:javascriptlet num = "123"; if (/^[0-9]*$/.test(num)) { console.log("Variable contains only numbers"); } else { console.log("Variable contains characters other than numbers"); }In this example, the
test()method of the regular expression checks if the variablenumcontains only numbers. If it does, it will output "Variable contains only numbers". If it contains characters other than numbers, it will output "Variable contains characters other than numbers".