Check if String is a Positive Integer in JavaScript-Code Examples

Radu TM

Check if String is a Positive Integer in JavaScript

JavaScript by Radu TM June 21, 2022

const isPositiveInteger = (str) => {
  // if the input string is not a positive integer, return false
  if (!/^\d+$/.test(str)) return false;

  // otherwise, return true
  return true;
}

0

20.069

Check if String is a Positive Integer in JavaScript

JavaScript by Radu TM June 21, 2022

const isPositiveInteger = (str) => {
  // if string is empty, it's not a positive integer
  if (str === '') return false;

  // if string includes anything other than digits, it's not a positive integer
  for (const char of str) {
    if (!/\d/.test(char)) return false;
  }

  // if string starts with '0', it's not a positive integer
  if (str.startsWith('0')) return false;

  // string is a positive integer
  return true;
};

0

20.069

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories