Javascript 正则表达式 - 使用允许列表的非法字符

发布于 12-24 17:14 字数 414 浏览 0 评论 0原文

我试图找到一种仅使用允许的字符列表来验证字符串的方法。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

治碍2024-12-31 17:14:32

您的正则表达式仅匹配单个字符。添加量词。

var reg = new RegExp('[' + allowed_chars + ']+');

'+' 表示“出现一次或多次”

您还想测试此模式是否与整个字符串匹配。添加行首和行尾标记。

var reg = new RegExp('^[' + allowed_chars + ']+

您可能还想在正则表达式中添加大写字母和空格。使用在线正则表达式测试器来调试正则表达式。

);

您可能还想在正则表达式中添加大写字母和空格。使用在线正则表达式测试器来调试正则表达式。

Your regex matches only single character. Add the quantifier.

var reg = new RegExp('[' + allowed_chars + ']+');

'+' 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.

var reg = new RegExp('^[' + allowed_chars + ']+

You might also want to add upper case letters and spaces to your regex. Use an online regex tester to debug your regular expressions.

);

You might also want to add upper case letters and spaces to your regex. Use an online regex tester to debug your regular expressions.

牵强ㄟ2024-12-31 17:14:32

您应该在正则表达式上添加 ^$

  var reg = new RegExp('^[' + allowed_chars + ']+
);

you should add ^ and $ on your regexp

  var reg = new RegExp('^[' + allowed_chars + ']+
);
把昨日还给我2024-12-31 17:14:32

您使用 element.match();
这个函数允许你匹配正则表达式

You use element.match();
this function allows you to match the Regexp

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文