FIX: Escape escape regexp characters.

This commit is contained in:
Guo Xiang Tan 2017-01-31 10:39:45 +08:00
parent 25516874b5
commit 058df4329d
2 changed files with 15 additions and 3 deletions

View File

@ -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);
}
}

View File

@ -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 &#9632;&#9632;&#9632;&#9632;&#9632;&#9632;, golly gee &#9632;&#9632;&#9632;&#9632;.</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. &#9632;&#9632;&#9632;&#9632;.</p>",
"it doesn't censor words unless they have boundaries.");
cooked("you are a whizzer! I love cheesewhiz. Whiz.",
"<p>you are a &#9632;&#9632;&#9632;&#9632;&#9632;&#9632;&#9632;! I love cheesewhiz. &#9632;&#9632;&#9632;&#9632;.</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\">&#9632;&#9632;&#9632;&#9632;</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 &#9632;&#9632;&#9632;&#9632;&#9632;&#9632;&#9632; the computer &#9632;&#9632;&#9632;&#9632; at 555-&#9632;&#9632;&#9632;&#9632;&#9632;&#9632;&#9632;&#9632; 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 &#9632;&#9632;&#9632;&#9632;&#9632;</p>",
"it escapes regexp chars");
});
test("code blocks/spans hoisting", function() {