javascript 正则表达式禁止所有特殊字符但允许在 jQuery 中使用德语变音符号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17153545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex to disallow all Special Chars but allow German Umlauts in jQuery?
提问by Thorsten
I would like to allow all Alphanumeric Characters and disallow all Special Characters in a RegEx. But I would like to allow German Umlauts but becouse they are Special Chars too, I can't type them in. I use this Script:
我想在 RegEx 中允许所有字母数字字符并禁止所有特殊字符。但我想允许德语变音,但因为它们也是特殊字符,我无法输入它们。我使用这个脚本:
if(website_media_description.match(/[^a-zA-Z0-9]/g)) {
alert('Found Special Char');
}
So when a ??ü??ü? is in the variable than I get the alert too. I also tryed this Script:
所以当 ??ü??ü? 是在变量中,而不是我收到警报。我也试过这个脚本:
if(website_media_description.match(/[^a-zA-Z0-9??ü??ü?]/g)) {
alert('Found Special Char');
}
But this also does not work. Can someone please tell me what I am doing wrong?
但这也行不通。有人可以告诉我我做错了什么吗?
Thanks :)
谢谢 :)
回答by Paul S.
my test String comes from an input field, i write "description test 1 ??ü??ü?"
我的测试字符串来自输入字段,我写“描述测试 1 ??ü??ü?”
Your problem is coming from the fact you haven't considered every character you want in your whitelist.
您的问题来自于您没有考虑白名单中想要的每个字符的事实。
Let's consider what is actually matched by your test string
让我们考虑一下您的测试字符串实际匹配的内容
"description test 1 ??ü??ü?".match(/[^a-zA-Z0-9??ü??ü?]/g);
// [" ", " ", " "]
As we can see, it matched 3 times, and each time was whitespace. So, the solution is to add a space to your whitelist (assuming you don't want to allow tab/return etc).
正如我们所见,它匹配了 3 次,每次都是空白。因此,解决方案是在白名单中添加一个空格(假设您不想允许 tab/return 等)。
"description test 1 ??ü??ü?".match(/[^a-zA-Z0-9??ü??ü? ]/g);
// null
Your test string now passes the RegExpwithout a match, which means it is valid in this case.
您的测试字符串现在通过了没有匹配项的RegExp,这意味着它在这种情况下是有效的。
回答by Thorsten
For some reason I needed to use the unicode representation:
出于某种原因,我需要使用 unicode 表示:
[^a-zA-Z0-9\u00E4\u00F6\u00FC\u00C4\u00D6\u00DC\u00df]`
Thanks to everyone :)
谢谢大家 :)