JavaScript - 檢查值是否為百分比?


假設我們的 value 如下所示 −

var value="97%";

若要檢查百分比的值,請使用正則表示式。

示例

以下為程式碼 −

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

若要執行以上程式,你需要使用以下命令 −

node fileName.js.

此處,我的檔名是 demo214.js。

輸出

在控制檯上的輸出如下 −

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

更新日期: 03-Oct-2020

1 千多次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.