正则验证函数异常:粘贴字符串验证失败,需移除非法字符
你的需求很明确:当前方法只是判断输入是否完全符合正则规则,不符合就返回false,但实际需要的是自动移除不符合规则的字符,保留合法内容,尤其是处理粘贴过来的包含特殊字符的文本时。
原方法的核心问题
你的skipMetadataSpecChar函数用val.match(...)做全量匹配校验——只有当整个字符串的每一个字符都在允许的范围内时才返回true,一旦出现非法字符(比如测试字符串里的ﻁﻁﻉﻁﻉﻁﻉ这类非ASCII字符),就直接返回false,完全没有处理非法字符的逻辑。
修改后的实现方案
我们把逻辑从「校验」改成「过滤」:用正则匹配所有不允许的字符,然后替换为空字符串,直接返回过滤后的合法内容。
function filterInvalidChars(val) { // 匹配所有不在允许列表中的字符,全局替换为空 return val.replace(/[^`_,:\\/="';%@#!~-&+^[\]{}$()<>|*?_\.,\s0-9a-zA-Z]/g, ''); }
代码细节说明:
- 正则规则调整:把原正则的
^[...](要求整个字符串由合法字符组成)改成[^...](匹配所有不在合法列表里的字符) - 添加
g修饰符:确保替换所有匹配到的非法字符,而不是只替换第一个 - 简化转义写法:原正则里的
\057(斜杠/)、\134(反斜杠\\)、\075(等号=)都换成了更易读的直接转义写法
测试你的示例文本
把你提供的测试字符串传入这个函数后,那些ﻁﻁﻉﻁﻉﻁﻉ这类非法字符会被自动移除,剩下的合法内容会完整保留,比如处理后会得到:
This is test comment for the length of text as there was a issue in prod due to comment length in the box.This is test comment for the length of text as there was a issue in prod due to comment length in the box.This is test comment for the length of text as there was a issue in prod due to comment length in the box.This is test comment for the length of text as there was a issue in prod due to comment length in the box.This is test comment for the length of text as there was a issue in prod due to comment length in the box.This is test comment for the length of text as there was a issue in prod due to comment length in the box.This is test comment for the length of text as there was a issue in prod due to comment length in the box.This is test comment for the length of text as there was a issue in prod due to comment length in the box.;%@#This is test comment for the length of text as there was a issue in prod due to comment length in the box. This is test data to vhe issue an$
额外扩展:保留校验功能
如果你还需要判断输入是否包含非法字符,可以在过滤后对比原字符串和结果:
function hasInvalidChars(val) { return val !== filterInvalidChars(val); }
这样就能同时满足「自动过滤非法字符」和「校验是否存在非法字符」的双重需求了。
内容的提问来源于stack exchange,提问作者Prashant Chaudhary

