使用 innerHTML 从 string.replace 打印正则表达式匹配项



我有一个禁止单词的列表,当用户尝试使用其中一个提交文本时,我希望有一个小警告,告诉他们他们使用的禁用单词。现在它可以工作,但由于某种原因只告诉他们他们使用的最后一个被禁止的词。

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Syntax Highlighting</title>
<!-- Main Quill library -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<style> #editor-container { height: 130px; } 
#banned-words { color: #660000; font-weight: bold; }</style>
</head>
<body>
<div id="form-container" class="container">
<form name="badwords" method="post" action="" >
<div class="row form-group">
<label for="about">Appraisal Info</label>
<input name="about" type="hidden">
<div id="banned-words"> </div>
<div id="editor-container">
</div>
</div>
<div class="row">
<button class="btn btn-primary" id="formSub" type="submit">Submit!</button>
</div>    
</form>
</div>
</body>
<script src="parch.js"></script>
<link href="style.css" rel="stylesheet">
<script type="text/javascript">
var div = document.getElementById('formSub'); 
function replaceWords(event) {
//Prevent form submission to server 
event.preventDefault();
var commentContent = quill.getText();
var badWords = ["green","yellow","blue"];
console.log(commentContent)
commentContent =censore(commentContent, badWords);
}   
function censore(string, filters) {
console.log('in')
// "i" is to ignore case and "g" for global "|" for OR match
var regex = new RegExp(filters.join("|"), "gi");
return string.replace(regex, function (match) {
var clean = match;
console.log(clean);
document.getElementById('banned-words').innerHTML = "Your description contained some sensitive words, please review the usage of the following words: " + match;
});
}
div.addEventListener('click',replaceWords); 
</script>
</html>

在此方法中

return string.replace(regex, function (match) {
var clean = match;
console.log(clean);
document.getElementById('banned-words').innerHTML = "Your description contained some sensitive words, please review the usage of the following words: " + match;
}

每次调用此方法时,您都会设置 innerHTML。字符串上的replace方法为每个匹配项调用匹配器函数。因此,它只会显示最后一个匹配的单词。换句话说,每次它找到匹配项时,它都会完全替换整个东西。

理想情况下,您将保留匹配列表,然后在审查功能结束时添加警告和整个列表。

最新更新