Skip to content
the poor coder

Javascript Regex for non-negative numbers

Poor Man
Published
Reading time
2 min read
On this page

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:

Text

/^\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:

Text

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:

Text

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:

Text

/^\d+$/

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

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC