仅替换段落中的单词

时间:2016-03-11 22:13:44

标签: javascript jquery html regex

我正在使用正则表达式替换<mark></mark>输入文本。我遇到的问题是它从持有者div获取所有文本并将其替换为变量并添加标记标记。然后将它放回div支架。当我执行此操作时,如果我输入"<p>",则会突出显示实际的<p>并将其输出回div。

有没有解决这个问题?这是我的标记代码:

function Search() {
    var Notes = document.getElementById("NoteHolder").innerHTML;
    var i = document.getElementById("Bar").value;
    var inputReOne = $.trim(i);
    var inp = inputReOne.replace(".", "\.").replace("<", "").replace(">", "").replace(
        "/", "").replace(/\\/, "");
    document.getElementById("Bar").value = inp;
    if ($.trim(inp) !== '') {
        var InpComp = inp.toUpperCase();
        var Ind = tags.indexOf(InpComp);
        if (Ind === -1) {
            var inpReg = new RegExp(inp, "im");
            var WordCheck = Notes.match(inpReg);
            if (WordCheck !== null) {
                tags.push(InpComp);
                var SearchReq = new RegExp("(" + inp + ")", "gim");
                var after = Notes.replace(SearchReq, "<mark class=" +
                    ColorOptionReady + ">$1</mark>");
                document.getElementById("NoteHolder").innerHTML = after;
            }

HTML:

<body>
   <div> 
       <p id="form"> 
           <input class="SearchInp" autocomplete="off" id="Bar" name="Input" type="text" placeholder="Search for word or phrase"> 
           <input class="SearchInp" type="submit" id="sea" onClick="Search ()" value="Search"> <div id="NoteHolder">
       </p>
       <p class="NoteOp" id="NoteOne">This is a test paragraph uses to TeSt filters.</p> 
       <p class="NoteOp" id="NoteTwo">Random words, I need to see if it will mess up mark</p> 
   </div>
<script src="Test.js"></script>
<script   src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js">    </script>
</body>

1 个答案:

答案 0 :(得分:0)

不是在#NoteHolder元素中搜索和替换,为什么不循环遍历每个.NoteOp并在那里替换?

&#13;
&#13;
function search() {
  var notes = document.getElementsByClassName("NoteOp");
  var s = document.getElementById("Bar").value.trim();
  for (var i = 0; i < notes.length; i++) {
    var n = notes[i];
    n.innerHTML = n.textContent.replace(new RegExp("(" + s + ")", "gim"), "<mark>$1</mark>");
  }
}
&#13;
<input class="SearchInp" autocomplete="off" id="Bar" name="Input" type="text" placeholder="Search for word or phrase">
<input class="SearchInp" type="submit" id="sea" onClick="search()" value="Search">
<div id="NoteHolder">
  <p class="NoteOp" id="NoteOne">This is a test paragraph uses to TeSt filters.</p>
  <p class="NoteOp" id="NoteTwo">Random words, I need to see if it will mess up mark</p>
</div>
&#13;
&#13;
&#13;

注意:将每个.NoteOp的内容存储在对象中,使用其中的文本并在每次搜索后简单地设置每个.NoteOp的内容将更容易和更清晰。