-1

I have a javascript function that replaces strings that match against a profanity library with symbols. eg. damn is transformed into @#$%&!

However, this replace is non-discriminating, and will transform partial matches as well. eg. classic is transformed into cl@#$%&!ic

I'm very new to TS/JS and Regex and would like some help understanding this function's arguments and how to modify them for only exact matches.

this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\\$&"), (ignore ? "gi" : "g")), (typeof (str2) == "string") ? str2.replace(/\$/g, "$$$$") : str2);

R A
  • 3
  • 1
  • Are you sure that regex is the tool you want? How complicated matches do you expect to need except full words? – Ted Lyngmo Oct 14 '22 at 16:49
  • At least not into [clbuttic](https://thedailywtf.com/articles/the-clbuttic-mistake-) – bobble bubble Oct 14 '22 at 16:53
  • Add word boundaries to the start and end of your regex (\b) – kelsny Oct 14 '22 at 17:06
  • @TedLyngmo I have an library array of "badwords" that some string is being compared against character by character. When the match is found, it replaces the part of the string with the chosen symbols. The regex function is originally what was provided by the guide, but I would like to modify this matching logic to be only full words rather than partial matches. – R A Oct 14 '22 at 17:10
  • @caTS - like so: ([\b\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&\b]) ? – R A Oct 14 '22 at 17:13

1 Answers1

0

To avoid partial matches, the normal solution is to surround what you want to match with word boundaries \b.

The following example assumes that profanities does not contain any words that contain regex special characters.

Notice that the "shit" in "mishit" and the "ass" in "class" do not get replaced.

const profanities = ['damn', 'shit', 'ass'];

// As regex literal: /\b(?:damn|shit|ass)\b/
const re = new RegExp('\\b(?:' + profanities.join('|') + ')\\b', 'gi');

const text = "Damn, another mishit. I am shit at pool. Time to get my ass to class."; 

console.log(text.replace(re, '@#$%&!'));
MikeM
  • 13,156
  • 2
  • 34
  • 47
  • Thanks @MikeM. I was able to adapt this to my code as such: `return this.replace(new RegExp('\\b(?:' +str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g, "\$&")+')\\b', (ignore ? "gi" : "g")), (typeof (str2) == "string") ? str2.replace(/\$/g, "$$$$") : str2);` – R A Oct 14 '22 at 19:07