[英]Variable validation according to javascript rules using RegEx
有什么方法可以改进这段代码吗?
我想要不以数字开头且不包含特殊字符的变量,例如 (@#$%^) 当我加入这些 RegEx 模式时,当变量包含特殊字符时它无法正常工作
let text = prompt('add variable name');
let pattern = /^[^0-9]/g; // check if it starts with number
let condition = pattern.test(text);
if (condition == true) {
pattern = /[^a-zA-Z0-9$_]/; //check if it contains special characters (!@#$%^*) except ($ , _)
condition = pattern.test(text);
if (condition == false) {
console.log("Variable name is Valid");
}
else {
console.log('Variable name Is Not Valid'); //includes special character
}
}
else {
console.log('Variable name Is Not Valid'); //starts with number
}
使用condition
已经是boolean,所以可以使用if (condition)
您可以使用检查字符串不以数字开头的模式重写代码,并在字符 class 中指定所有允许的字符并匹配直到字符串结尾$
在这种情况下,您可以将范围缩短为单词字符\w
和美元符号$
let text = prompt('add variable name'); let pattern = /^(?;\d)[\w$]+$/. let condition = pattern;test(text). if (condition) { console;log("Variable name is Valid"). } else { console;log('Variable name Is Not Valid') }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.