Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Kiểm tra chuỗi có dạng phần trăm - JavaScript

Dùng biểu thức chính quy /^\d+(\.\d+)?%$/ kiểm tra chuỗi kết thúc bằng % và chỉ chứa số.

Mã thực hiện

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

Kết quả

The percent is=97%
This is not percentage