How To Check If String Is A Positive Integer Using JavaScript

Check if String is a Positive Integer using JavaScript

Let’s follow this article to learn how to check if string is a positive integer using JavaScript with the explanation and examples below. Read this article now.

Check If String Is A Positive Integer Using JavaScript

To check if string is a positive integer using JavaScript, you have to convert a string to an integer or a number. 

Next, if you convert it to a number, you have to check if it is an integer or not.

Then, you can get the result of the problem by checking if the result of the previous step is greater than or equal to 0 or not.

You can learn more about methods that can help you convert a string to a number or an integer here.

Use the parseInt() method

You can convert the string to an integer by the parseInt() method. So you can get the result by comparing it with 0.

Look at the example below to learn more about this method.

// This is the function that helps you check if String is a Positive Integer.
function isPositiveInteger(str){

    // Check if a String can be a Float or not.
    if (str.includes('.')) return false
    
    let value = parseInt(str)

    if (isNaN(value)) return false
    if ( value < 0 ) return false

    return true
}

let str1 = '1'
let str2 = 'LearnShareIT'
let str3 = '0.5'
let str4 = '-1'
let str5= '0'

console.log(isPositiveInteger(str1))
console.log(isPositiveInteger(str2))
console.log(isPositiveInteger(str3))
console.log(isPositiveInteger(str4))
console.log(isPositiveInteger(str5))

Output

true 
false 
false
false
true

Use the Number object

Firstly, you convert the string to a number.

Secondly, check if the number is an integer or not by using the isInteger() method.

Finally, check if an integer is greater than or equal to 0.

You will get the result of the task.

Syntax

Number.isInteger(value)

Parameters

  • value: The value you want to check.

Return Value:

True if the value is an integer. Otherwise false.

Look at the example below:

// This is the function that helps you check if String is a Positive Integer.
function isPositiveInteger(str){
    let value = Number(str)

    if ( isNaN(value) || Number.isInteger(value) == false) return false
    if (value < 0 ) return false

    return true
}

let str1 = '1'
let str2 = 'LearnShareIT'
let str3 = '0.5'
let str4 = '-1'
let str5= '0'

console.log(isPositiveInteger(str1))
console.log(isPositiveInteger(str2))
console.log(isPositiveInteger(str3))
console.log(isPositiveInteger(str4))
console.log(isPositiveInteger(str5))

Output

true 
false 
false
false
true

Summary

You can check if string is a positive integer using JavaScript by using the parseInt() method or the Number object. Choose the method that is suitable for you. We hope this guide is helpful to you. Thanks!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *