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, '*');
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745203639a4616476.html
评论列表(0条)