admin管理员组文章数量:1415421
I need a regex that will match a certain string and replace each letter of it with a symbol.
So... "Cheese"
would be replaced by "******"
but "Pie"
would be replaced by "***"
So for example:
"my pie is tasty and so is cake".replace(new RegExp(/(pizza|cake|pie|test|horseshoe)/gi), "'*' x length($1)")
(Obviously the substitution doesn't exist)
I need a regex that will match a certain string and replace each letter of it with a symbol.
So... "Cheese"
would be replaced by "******"
but "Pie"
would be replaced by "***"
So for example:
"my pie is tasty and so is cake".replace(new RegExp(/(pizza|cake|pie|test|horseshoe)/gi), "'*' x length($1)")
(Obviously the substitution doesn't exist)
Share Improve this question edited Dec 23, 2012 at 15:40 Bhavik Ambani 6,66715 gold badges58 silver badges87 bronze badges asked Dec 23, 2012 at 15:37 user1925170user1925170 2- 9 Please read en.wikipedia/wiki/Clbuttic and codinghorror./blog/2008/10/… before adding such a filter. – ThiefMaster Commented Dec 23, 2012 at 15:39
- See also this Stack Overflow answer for the most thorough explanation of why this is a stillborn idea. If you filter pie, people will use рie, or pіe, or piе, or ріе, or any of the thousands of other tricks. (You don't see a difference between those? Precisely! But your regex will.) – ЯegDwight Commented Dec 23, 2012 at 16:04
3 Answers
Reset to default 5Personally I think this is a very bad idea, because:
- It will mangle valid text which can annoy valid users.
- It is easy to trick the filter by using misspellings so it won't hinder malicious users.
However to solve your problem you can pass a function to replace:
var regex = /(pizza|cake|pie|test|horseshoe)/gi;
var s = "my pie is tasty and so is cake";
s = s.replace(regex, function(match) { return match.replace(/./g, '*'); });
Disclaimer: These filters don't work.. That being said, you would want to use the callback function with replace
:
"my pie is tasty and so is cake".replace(/(pizza|cake|pie|test|horseshoe)/gi, function (match) {
return match.replace(/./g, '*');
});
Working example: http://jsfiddle/mRF9m/
To prevent the aforementioned classic issue by @ThiefMaster you might consider adding word boundaries to the pattern. However, keep in mind that you will still have to take care of the plural and misspelled forms of those words as well.
var str = 'pie and cake are tasty but not spies or protests';
str = str.replace(/\b(pizza|cake|pie|test|horseshoe)\b/gi, function (match) {
return match.replace(/\w/g, '*');
});
本文标签: javascriptSwear Filter RegexStack Overflow
版权声明:本文标题:javascript - Swear Filter Regex - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745203639a2647523.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论