Check If Value Is a Percentage in JavaScript



To check the value for percentage, use a regular expression. When dealing with user input or processing data in JavaScript, it's important to make sure a value is a valid percentage. This article shows you how to check if a value is a percentage using JavaScript, highlighting a useful method that involves regular expressions.

Let's say the following is our value

var value="97%";

To check the value for percentage, we are using a regular expression.

Using Regular Expression

The best way to check if a string is in the correct percentage format is by using regular expressions. A regular expression sets the specific pattern that is used to check a valid percentage value.

Implementation Steps

To achieve this, follow the steps mentioned below:

  • Declare a Variable: Create a variable (such as: value) and assign it a string that represents a percentage (e.g., "97%").
  • Define and Execute the Regular Expression: Use a regular expression to check if the value is in the percentage format. The test() method will give you either true or false.
  • Check the Result: Use an if statement to see if the result is true. If it is, print a message saying that it is a valid percentage.
  • Handle Invalid Percentage: If the result is not true, log a message indicating that the value is not a percentage.
  • Repeat the process while reasigning a value to check valid percentage value.

Example

The following is an example for checking a value is a percentage or not.

var value="97%";
var result=/^\d+(\.\d+)?%$/.test(value);
if (result==true) {
    console.log("The percent is="+value);  
}
else
{
    console.log("This is not percentage");  
}
var value1="percent";
var result1=/^\d+(\.\d+)?%$/.test(value1);
if (result1==true) {
    console.log("The percent is="+value1);  
}
else
{
    console.log("This is not percentage");  
}

Output

The percent is=97%
This is not percentage

Conclusion

In this article, we have created a simple program that is used to efficiently check if the value is a percentage or not in JavaScript. In this article, we have used a regular expression, which is a simple way of checking a value.

Updated on: 2025-02-25T14:50:05+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements