How to Check if String is a Positive Integer in JavaScript
Table of Contents
Sometimes you will come across strings that contain numbers, or are entirely made up of numbers.
When this happens, you might want to be able to check if the string is a positive integer so you can do some math with it.
In this post, we'll learn how to check if a string is a positive integer in JavaScript.
How to check if a string is a positive integer
To begin, let's start off with our example string:
JAVASCRIPTconst string = "123";
To check if a string is a positive integer, we first must convert the string into a number.
We can do this by using the Number
constructor.
JAVASCRIPTconst string = "123";
const number = Number(string);
console.log(number);
BASH123
Now we must determine if this number is an integer.
We can do this by using the Number.isInteger()
function, which accepts a string and returns a boolean value.
JAVASCRIPTconst string = "123";
const number = Number(string);
const isInteger = Number.isInteger(number);
console.log(isInteger);
BASHtrue
Now that we've determined the number is an integer, we can just check that it is greater than 0 to confirm that it is a positive integer:
JAVASCRIPTconst string = "123";
const number = Number(string);
const isInteger = Number.isInteger(number);
const isPositive = number > 0;
const isPositiveInteger = isInteger && isPositive;
console.log(isPositiveInteger);
BASHtrue
We can wrap this up into a reusable function:
JAVASCRIPTconst isPositiveInteger = string => {
const number = Number(string);
const isInteger = Number.isInteger(number);
const isPositive = number > 0;
return isInteger && isPositive;
}
const results = isPositiveInteger("123");
console.log(results);
BASHtrue
Conclusion
In this post, we learned how to check if a string is an integer greater than 0.
Simply use the Number
constructor to convert the string into a number, and then use the Number.isInteger()
function to determine if the number is an integer, then check if the number is greater than 0.
Thanks for reading!
- Managing PHP Dependencies with Composer
- Getting Started with Express
- How to deploy a .NET app using Docker
- How to deploy a PHP app using Docker
- How to deploy an Express app using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with Vuex: Managing State in Vue