JavaScript - Check if value is a percentage?


Let’s say the following is our value −

var value="97%";

To check the value for percentage, use regular expression.

Example

Following is the code −

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");  
}

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo214.js.

Output

The output is as follows on console −

PS C:\Users\Amit\JavaScript-code> node demo214.js
The percent is=97%
This is not percentage

Updated on: 03-Oct-2020

871 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements