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

时间:2018-06-11 16:55:49

标签: javascript jquery regex

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

<!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>

1 个答案:

答案 0 :(得分:0)

在这个方法中

 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方法为每个匹配调用匹配器函数。所以它只会显示最后一个匹配的单词。换句话说,每次找到匹配时,它都会完全取代整个事物。

理想情况下,您会保留一份匹配列表,然后在审查员功能的末尾添加警告和整个列表。