2

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)

Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86
  • 9
    Please read http://en.wikipedia.org/wiki/Clbuttic and http://www.codinghorror.com/blog/2008/10/obscenity-filters-bad-idea-or-incredibly-intercoursing-bad-idea.html before adding such a filter. – ThiefMaster Dec 23 '12 at 15:39
  • See also [this Stack Overflow answer](http://stackoverflow.com/a/6099598/58792) 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 Dec 23 '12 at 16:04

3 Answers3

5

Personally 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, '*'); });
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
3

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.net/mRF9m/

jbabey
  • 45,965
  • 12
  • 71
  • 94
0

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, '*');
});
Geo
  • 12,666
  • 4
  • 40
  • 55