且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式禁止所有特殊字符但允许jQuery中的德语变音符号?

更新时间:2023-02-22 13:57:27


我的测试字符串来自输入字段,我写描述测试1öäüÖÄÜß

my test String comes from an input field, i write "description test 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);
// [" ", " ", " "]

我们可以看到,它匹配3次,每次都是空白。因此,解决方案是为您的白名单添加一个空格(假设您不想允许标签/返回等)。

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).

"description test 1 öäüÖÄÜß".match(/[^a-zA-Z0-9äöüÄÖÜß ]/g);
// null

您的测试字符串现在通过 RegExp 没有匹配,这意味着它在这种情况下有效。

Your test string now passes the RegExp without a match, which means it is valid in this case.