Javascript 正则表达式 - 使用允许列表的非法字符
我试图找到一种仅使用允许的字符列表来验证字符串的方法。
var valid = validate('This is my string!', 'abcdefghijklmnopqrstuvwxyz');
function validate(value, allowed_chars){
var reg = new RegExp('[' + allowed_chars + ']');
var valid = reg.test(value);
return valid;
}
在这种情况下,我希望函数返回 false,因为它在字符串中有感叹号,并且尚未放入允许的字符中。有什么想法吗?
非常感谢您的帮助,谢谢!
我不想使用循环来检查每个字符。
I am trying to find a method to validate a string, using a list of allowed characters only.
var valid = validate('This is my string!', 'abcdefghijklmnopqrstuvwxyz');
function validate(value, allowed_chars){
var reg = new RegExp('[' + allowed_chars + ']');
var valid = reg.test(value);
return valid;
}
In this case, I wish for the function to return false because it has an exclamation mark in the string and that hasn't been put in the allowed characters. Any ideas?
Help is much appreciated, Thankyou!
I do not wish to use a loop to check each character.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您的正则表达式仅匹配单个字符。添加量词。
'+' 表示“出现一次或多次”
您还想测试此模式是否与整个字符串匹配。添加行首和行尾标记。
您可能还想在正则表达式中添加大写字母和空格。使用在线正则表达式测试器来调试正则表达式。
Your regex matches only single character. Add the quantifier.
'+' means 'one or more occurences of this'
You also want to test if this pattern matches the entire string. Add markers for beginning and end of line.
You might also want to add upper case letters and spaces to your regex. Use an online regex tester to debug your regular expressions.