繁体   English   中英

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

[英]Printing regex matches from string.replace using innerHTML

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

<!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方法为每个匹配项调用matcher函数。 因此,它将仅显示最后一个匹配的单词。 换句话说,每次找到匹配项时,它将完全替换整个事物。

理想情况下,您将保留一个匹配项列表,然后在检查器功能的末尾添加警告和整个列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM