如果允許使用者隨意輸入, 容易有風險, 如果只允許大小寫英文與減號, 寫法如下:
let filename = "abc-xyz";
let pattern = "^[-a-zA-Z0-9]+$";
if (filename.match(pattern)) {
console.log('yes');
} else {
console.log('no');
}
範例1:
var folder = 'fsvdsv_$ve';
if (folder.match("^[a-zA-Z0-9_]+$")) {
console.log('yes');
} else {
console.log('no');
}
範例2:
const re = new RegExp(/[a-zA-Z0-9*]/g);
console.log("*".match(re)); // match
console.log("123".match(re)); // match
console.log("abc".match(re)); // match
console.log("!@#$%^&".match(re)); // null
console.log("123!".match(re)); // Will match 1, 2, and 3 but not !
相關文章
Matching 0-9, a-z, and 1 special character in JavaScript Regex
https://stackoverflow.com/questions/54835478/matching-0-9-a-z-and-1-special-character-in-javascript-regex
java 字串, 只允許特定白名單
https://stackoverflow.max-everyday.com/2023/09/java-string-match-regex/