mirror of
https://github.com/discourse/discourse.git
synced 2024-11-29 04:03:57 -06:00
FIX: Escape escape regexp characters.
This commit is contained in:
parent
25516874b5
commit
058df4329d
@ -1,9 +1,13 @@
|
||||
function escapeRegexp(text) {
|
||||
return text.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&')
|
||||
}
|
||||
|
||||
export function censor(text, censoredWords, censoredPattern) {
|
||||
let patterns = [],
|
||||
originalText = text;
|
||||
|
||||
if (censoredWords && censoredWords.length) {
|
||||
patterns = censoredWords.split("|").map(t => { return "(" + t.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&') + ")"; });
|
||||
patterns = censoredWords.split("|").map(t => `(${escapeRegexp(t)})`);
|
||||
}
|
||||
|
||||
if (censoredPattern && censoredPattern.length > 0) {
|
||||
@ -22,7 +26,7 @@ export function censor(text, censoredWords, censoredPattern) {
|
||||
while (m && m[0]) {
|
||||
if (m[0].length > originalText.length) { return originalText; } // regex is dangerous
|
||||
const replacement = new Array(m[0].length+1).join('■');
|
||||
text = text.replace(new RegExp("(\\b" + m[0] + "\\b)(?![^\\(]*\\))", "ig"), replacement);
|
||||
text = text.replace(new RegExp(`(\\b${escapeRegexp(m[0])}\\b)(?![^\\(]*\\))`, "ig"), replacement);
|
||||
m = censorRegexp.exec(text);
|
||||
}
|
||||
}
|
||||
|
@ -11,7 +11,7 @@ const defaultOpts = buildOptions({
|
||||
emoji_set: 'emoji_one',
|
||||
highlighted_languages: 'json|ruby|javascript',
|
||||
default_code_lang: 'auto',
|
||||
censored_words: 'shucks|whiz|whizzer',
|
||||
censored_words: 'shucks|whiz|whizzer|a**le',
|
||||
censored_pattern: '\\d{3}-\\d{4}|tech\\w*'
|
||||
},
|
||||
getURL: url => url
|
||||
@ -524,18 +524,26 @@ test("censoring", function() {
|
||||
cooked("aw shucks, golly gee whiz.",
|
||||
"<p>aw ■■■■■■, golly gee ■■■■.</p>",
|
||||
"it censors words in the Site Settings");
|
||||
|
||||
cooked("you are a whizzard! I love cheesewhiz. Whiz.",
|
||||
"<p>you are a whizzard! I love cheesewhiz. ■■■■.</p>",
|
||||
"it doesn't censor words unless they have boundaries.");
|
||||
|
||||
cooked("you are a whizzer! I love cheesewhiz. Whiz.",
|
||||
"<p>you are a ■■■■■■■! I love cheesewhiz. ■■■■.</p>",
|
||||
"it censors words even if previous partial matches exist.");
|
||||
|
||||
cooked("The link still works. [whiz](http://www.whiz.com)",
|
||||
"<p>The link still works. <a href=\"http://www.whiz.com\">■■■■</a></p>",
|
||||
"it won't break links by censoring them.");
|
||||
|
||||
cooked("Call techapj the computer whiz at 555-555-1234 for free help.",
|
||||
"<p>Call ■■■■■■■ the computer ■■■■ at 555-■■■■■■■■ for free help.</p>",
|
||||
"uses both censored words and patterns from site settings");
|
||||
|
||||
cooked("I have a pen, I have an a**le",
|
||||
"<p>I have a pen, I have an ■■■■■</p>",
|
||||
"it escapes regexp chars");
|
||||
});
|
||||
|
||||
test("code blocks/spans hoisting", function() {
|
||||
|
Loading…
Reference in New Issue
Block a user