[英]How to check string against whitelisted characters in JavaScript?
I have a bit of code that transforms user input to ensure the only allowed characters are abcdefghijklmnopqrstuvwxyz-0123456789我有一些代码可以转换用户输入以确保唯一允许的字符是 abcdefghijklmnopqrstuvwxyz-0123456789
https://jsfiddle.net/py4pnr0L/ https://jsfiddle.net/py4pnr0L/
value = 'GHJHlk;sxa787BVK'
value = value.toLowerCase()
value = value.replace(/[^a-z0-9\-]/gi, '-')
console.log(value)
Returns: ghjhlk-sxa787bvk返回:ghjhlk-sxa787bvk
How would I go about not transforming, but just testing to find if a given string contains characters outside the permitted range?我将如何不进行转换,而只是测试以查找给定字符串是否包含超出允许范围的字符?
All I want to know is true/false for a given input string.我想知道的是给定输入字符串的真/假。
I am using ES2015 so if the cleanest solution is available using ES2015 then that is fine.我使用的是 ES2015,所以如果使用 ES2015 可以使用最干净的解决方案,那就没问题了。
you can use match method , try something like:您可以使用 match 方法,尝试以下操作:
value = 'GHJHlksxa787BVK'; console.log(!value.match(/[^a-zA-Z0-9\\-]/))
You can use RegExp#test()
method:您可以使用
RegExp#test()
方法:
Executes a search for a match between a regular expression and a specified string.
执行搜索正则表达式和指定字符串之间的匹配项。 Returns
true
orfalse
.返回
true
或false
。
No /g
modifier should be used with this method so that the lastIndex
property could not mess the results.此方法不应使用
/g
修饰符,以便lastIndex
属性不会弄乱结果。 See Why RegExp with global flag in Javascript give wrong results?请参阅为什么在 Javascript 中带有全局标志的 RegExp 会给出错误的结果? for details.
详情。
Your regex /[^a-z0-9-]/i
(matches any character that is not in the az
and AZ
and 0-9
ranges and not -
) can be used here.您的正则表达式
/[^a-z0-9-]/i
(匹配任何不在az
和AZ
和0-9
范围内的字符,而不是-
)可以在这里使用。 Just take out the /g
.只需取出
/g
。
var value = "GHJHlksxa787BVK"; document.body.innerHTML = /[^a-z0-9-]/i.test(value);
The /i
is a case insensitive modifier, /[az]/i
= /[A-Za-z]/
. /i
是不区分大小写的修饰符, /[az]/i
= /[A-Za-z]/
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.