regex only number except 0 in javascript

To match only numbers except 0 using regex in JavaScript, you can use a negative lookahead to exclude the digit 0 from the match:

const regex = /^[1-9]\d*$/;
28 chars
2 lines

This regular expression matches any string that starts with a non-zero digit and is followed by zero or more digits.

Here's an example of using the regex to test if a string is a non-zero number:

const str = '42';
const isNonZeroNumber = regex.test(str);
console.log(isNonZeroNumber); // true

const str2 = '0';
const isNonZeroNumber2 = regex.test(str2);
console.log(isNonZeroNumber2); // false
199 chars
8 lines

In the example above, isNonZeroNumber is true because str is a non-zero number. isNonZeroNumber2 is false because str2 is the digit 0 which is excluded by the regex.

gistlibby LogSnag