Javascript Regex for non-negative numbers

Javascript Regex for non-negative numbers

If you are working with user input in your Javascript code and you want to validate that the input is a non-negative number, you can use regular expressions or regex to do so. A regex is a pattern that specifies a set of strings to match or find in a given input. In this case, we want to match strings that represent non-negative numbers.

Using regex to match non-negative numbers

To match non-negative numbers using regex in Javascript, we can use the following pattern:


/^\d+(\.\d+)?$/

This pattern matches strings that start with one or more digits followed by an optional decimal point and one or more digits. This allows for numbers like "10", "100.5", "0.5", and "0".

We can use the test() method of the regex object in Javascript to check if a given string matches this pattern:


const regex = /^\d+(\.\d+)?$/;

function isNonNegativeNumber(input) {
  return regex.test(input);
}

console.log(isNonNegativeNumber("10")); // true
console.log(isNonNegativeNumber("100.5")); // true
console.log(isNonNegativeNumber("0.5")); // true
console.log(isNonNegativeNumber("0")); // true
console.log(isNonNegativeNumber("-10")); // false
console.log(isNonNegativeNumber("abc")); // false

By wrapping the regex pattern in forward slashes (/) and using the RegExp constructor, we can also create a regex object directly:


const regex = new RegExp("^\\d+(\\.\\d+)?$");

Matching integers only

If you want to match only integers (no decimal points), you can modify the regex pattern to:


/^\d+$/

This pattern matches strings that consist of one or more digits only:


const regex = /^\d+$/;

console.log(regex.test("10")); // true
console.log(regex.test("100.5")); // false
console.log(regex.test("0.5")); // false
console.log(regex.test("0")); // true

Conclusion

Regex is a powerful tool for validating and manipulating strings in Javascript. By using regex patterns, we can easily match non-negative numbers and other types of input in our code.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe