Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8013357
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T19:36:48+00:00 2026-06-04T19:36:48+00:00

I would like the simplest fail-safe test to check that a string in JavaScript

  • 0

I would like the simplest fail-safe test to check that a string in JavaScript is a positive integer.

isNaN(str) returns true for all sorts of non-integer values and parseInt(str) is returning integers for float strings, like “2.5”. And I don’t want to have to use some jQuery plugin either.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T19:36:49+00:00Added an answer on June 4, 2026 at 7:36 pm

    Two answers for you:

    • Based on parsing

    • Regular expression

    Note that in both cases, I’ve interpreted "positive integer" to include 0, even though 0 is not positive. I include notes if you want to disallow 0.

    Based on Parsing

    If you want it to be a normalized decimal integer string over a reasonable range of values, you can do this:

    function isInDesiredForm(str) {
        var n = Math.floor(Number(str));
        return n !== Infinity && String(n) === str && n >= 0;
    }
    

    or if you want to allow whitespace and leading zeros:

    function isInDesiredForm(str) {
        str = str.trim();
        if (!str) {
            return false;
        }
        str = str.replace(/^0+/, "") || "0";
        var n = Math.floor(Number(str));
        return n !== Infinity && String(n) === str && n >= 0;
    }
    

    Live testbed (without handling leading zeros or whitespace):

    function isInDesiredForm(str) {
        var n = Math.floor(Number(str));
        return n !== Infinity && String(n) === str && n >= 0;
    }
    function gid(id) {
        return document.getElementById(id);
    }
    function test(str, expect) {
        var result = isInDesiredForm(str);
        console.log(
            str + ": " +
            (result ? "Yes" : "No") +
            (expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***")
        );
    }
    gid("btn").addEventListener(
        "click",
        function() {
            test(gid("text").value);
        },
        false
    );
    test("1", true);
    test("1.23", false);
    test("1234567890123", true);
    test("1234567890123.1", false);
    test("0123", false); // false because we don't handle leading 0s
    test(" 123 ", false); // false because we don't handle whitespace
    <label>
      String:
      <input id="text" type="text" value="">
    <label>
    <input id="btn" type="button" value="Check">

    Live testbed (with handling for leading zeros and whitespace):

    function isInDesiredForm(str) {
        str = str.trim();
        if (!str) {
            return false;
        }
        str = str.replace(/^0+/, "") || "0";
        var n = Math.floor(Number(str));
        return String(n) === str && n >= 0;
    }
    function gid(id) {
        return document.getElementById(id);
    }
    function test(str, expect) {
        var result = isInDesiredForm(str);
        console.log(
            str + ": " +
            (result ? "Yes" : "No") +
            (expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***")
        );
    }
    gid("btn").addEventListener(
        "click",
        function() {
            test(gid("text").value);
        },
        false
    );
    test("1", true);
    test("1.23", false);
    test("1234567890123", true);
    test("1234567890123.1", false);
    test("0123", true);
    test(" 123 ", true);
    <label>
      String:
      <input id="text" type="text" value="">
    <label>
    <input id="btn" type="button" value="Check">

    If you want to disallow 0, just change >= 0 to > 0. (Or, in the version that allows leading zeros, remove the || "0" on the replace line.)

    How that works:

    1. In the version allowing whitespace and leading zeros:
    • str = str.trim(); removes any leading and trailing whitepace.
    • if (!str) catches a blank string and returns, no point in doing the rest of the work.
    • str = str.replace(/^0+/, "") || "0"; removes all leading 0s from the string — but if that results in a blank string, restores a single 0.
    1. Number(str): Convert str to a number; the number may well have a fractional portion, or may be NaN.

    2. Math.floor: Truncate the number (chops off any fractional portion).

    3. String(...): Converts the result back into a normal decimal string. For really big numbers, this will go to scientific notation, which may break this approach. (I don’t quite know where the split is, the details are in the spec, but for whole numbers I believe it’s at the point you’ve exceeded 21 digits [by which time the number has become very imprecise, as IEEE-754 double-precision numbers only have roughtly 15 digits of precision..)

    4. ... === str: Compares that to the original string.

    5. n >= 0: Check that it’s positive.

    Note that this fails for the input "+1", any input in scientific notation that doesn’t turn back into the same scientific notation at the String(...) stage, and for any value that the kind of number JavaScript uses (IEEE-754 double-precision binary floating point) can’t accurately represent which parses as closer to a different value than the given one (which includes many integers over 9,007,199,254,740,992; for instance, 1234567890123456789 will fail). The former is an easy fix, the latter two not so much.

    Regular Expression

    The other approach is to test the characters of the string via a regular expression, if your goal is to just allow (say) an optional + followed by either 0 or a string in normal decimal format:

    function isInDesiredForm(str) {
        return /^\+?(0|[1-9]\d*)$/.test(str);
    }
    

    Live testbed:

    function isInDesiredForm(str) {
        return /^\+?(0|[1-9]\d*)$/.test(str);
    }
    function gid(id) {
        return document.getElementById(id);
    }
    function test(str, expect) {
        var result = isInDesiredForm(str);
        console.log(
            str + ": " +
            (result ? "Yes" : "No") +
            (expect === undefined ? "" : !!expect === !!result ? " <= OK" : " <= ERROR ***")
        );
    }
    gid("btn").addEventListener(
        "click",
        function() {
            test(gid("text").value);
        },
        false
    );
    test("1", true);
    test("1.23", false);
    test("1234567890123", true);
    test("1234567890123.1", false);
    test("0123", false); // false because we don't handle leading 0s
    test(" 123 ", false); // false because we don't handle whitespace
    <label>
      String:
      <input id="text" type="text" value="">
    <label>
    <input id="btn" type="button" value="Check">

    How that works:

    1. ^: Match start of string

    2. \+?: Allow a single, optional + (remove this if you don’t want to)

    3. (?:...|...): Allow one of these two options (without creating a capture group):

    4. (0|...): Allow 0 on its own…

    5. (...|[1-9]\d*): …or a number starting with something other than 0 and followed by any number of decimal digits.

    6. $: Match end of string.

    If you want to disallow 0 (because it’s not positive), the regular expression becomes just /^\+?[1-9]\d*$/ (e.g., we can lose the alternation that we needed to allow 0).

    If you want to allow leading zeroes (0123, 00524), then just replace the alternation (?:0|[1-9]\d*) with \d+

    function isInDesiredForm(str) {
        return /^\+?\d+$/.test(str);
    }
    

    If you want to allow whitespace, add \s* just after ^ and \s* just before $.

    Note for when you convert that to a number: On modern engines it would probably be fine to use +str or Number(str) to do it, but older ones might extend those in a non-standard (but formerly-allowed) way that says a leading zero means octal (base 8), e.g "010" => 8. Once you’ve validated the number, you can safely use parseInt(str, 10) to ensure that it’s parsed as decimal (base 10). parseInt would ignore garbage at the end of the string, but we’ve ensured there isn’t any with the regex.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

For TDD you have to Create a test that fail Do the simplest thing
I would like to create the simplest (hello world package) package that I could
I would like to create a method that returns an XmlReader. Depending on the
The simplest example would be the built in class keyValuePair(of T,U). I would like
Would like to make anapplication in Java that will not automatically parse parameters used
I would like to recreate the interface below that allows the user to select
I would like to maintain a list of objects that is distributed between N
I would like to know the simplest solution to changing the underscores of my
I would like to know what the simplest/best way for obtaining information about the
I would like to have a compareTo method that ignores the time portion of

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.