Home > Enterprise >  Search and replace text in HTML without removing html formatting
Search and replace text in HTML without removing html formatting

Time:08-18

I have this code to find and highlight text in html

const p = document.getElementById("content");
function search() {
let input = document.getElementById("input").value;
      if (input !== "") {
        let regExp = new RegExp(input, "gi");
        p.innerHTML = (p.textContent).replace(regExp, "<span style='background-color:yellow;'>$&</span>");
        
      } 
    }
<nav >
    <div >
      <h1 >HTML Search Bar</h1>
      <input  type="text" placeholder="Search" aria-label="Search" id="input"
        onkeyup="search();">
    </div>
  </nav>
 <div id="content">
Phasellus consequat congue neque ac consequat. Proin ultricies risus lorem, et scelerisque lectus imperdiet vitae. Vestibulum pretium eget mauris a interdum. Donec a justo nisl. Morbi vel ante eget lectus euismod auctor. Duis interdum lobortis eros at tincidunt. Proin id egestas lectus, eu varius enim. Aliquam elit arcu, dictum at cursus non, dignissim eleifend augue. Pellentesque iaculis quis felis eu ullamcorper. Duis at sollicitudin magna, ac gravida lectus. Phasellus consectetur neque tellus, a auctor lacus fringilla eget. Proin arcu orci, auctor eu diam vitae, ultricies tincidunt dolor. Nunc sit amet magna nisl. Vivamus at nisl mattis nulla aliquam semper.
<br>
<br>
<br>
Nullam convallis leo vel magna vulputate, sed tempor nibh elementum. Cras a dui vitae odio posuere interdum. Nam interdum consequat convallis. Fusce dolor ligula, sollicitudin sed massa sed, tempus imperdiet mi. Donec vel mauris nec velit volutpat dictum. Vivamus ut erat quam. Aliquam rhoncus elit venenatis imperdiet blandit. Proin feugiat accumsan nibh quis rutrum. Quisque consequat lacinia risus id vulputate. Etiam tristique quis odio sed consequat. In in justo pharetra, dignissim metus at, sollicitudin elit. Nullam vulputate turpis libero, quis sodales ante volutpat non.
</div>

I am having three problems:

  1. after search the formatting of HTML is remove, line breaks are not working after search
  2. searching for full stop highlights the whole text
  3. after search word is removed one letter still remains highlighted

CodePudding user response:

The formatting gets lost because you are using p.textContent which only includes the text.

In my answer I remove ALL spans for every key that way it will fix the problem with emptying an existing search still has the first letter highlighted. Also, I'm using p.innerHTML to search within so I don't lose the past formats.

Also, I'm not using regular expressions as that isn't reliable for parsing HTML.

const p = document.getElementById("content");

function search() {
  let input = document.getElementById("input").value;
  spans = p.querySelectorAll("span");

  spans.forEach(function(span){
    span.outerHTML = span.innerText;
  })

  if (input !== "") {
    let regExp = new RegExp(input, "gi");
    p.innerHTML = (p.innerHTML).replace(regExp, "<span style='background-color:yellow;'>$&</span>");

  }
}
<nav >
  <div >
    <h1 >HTML Search Bar</h1>
    <input  type="text" placeholder="Search" aria-label="Search" id="input" onkeyup="search();">
  </div>
</nav>
<div id="content">
  Phasellus consequat congue neque ac consequat. Proin ultricies risus lorem, et scelerisque lectus imperdiet vitae. Vestibulum pretium eget mauris a interdum. Donec a justo nisl. Morbi vel ante eget lectus euismod auctor. Duis interdum lobortis eros at
  tincidunt. Proin id egestas lectus, eu varius enim. Aliquam elit arcu, dictum at cursus non, dignissim eleifend augue. Pellentesque iaculis quis felis eu ullamcorper. Duis at sollicitudin magna, ac gravida lectus. Phasellus consectetur neque tellus,
  a auctor lacus fringilla eget. Proin arcu orci, auctor eu diam vitae, ultricies tincidunt dolor. Nunc sit amet magna nisl. Vivamus at nisl mattis nulla aliquam semper. NEW LINE
  <br>
  <br>
  <br> Nullam convallis leo vel magna vulputate, sed tempor nibh elementum. Cras a dui vitae odio posuere interdum. Nam interdum consequat convallis. Fusce dolor ligula, sollicitudin sed massa sed, tempus imperdiet mi. Donec vel mauris nec velit volutpat
  dictum. Vivamus ut erat quam. Aliquam rhoncus elit venenatis imperdiet blandit. Proin feugiat accumsan nibh quis rutrum. Quisque consequat lacinia risus id vulputate. Etiam tristique quis odio sed consequat. In in justo pharetra, dignissim metus at,
  sollicitudin elit. Nullam vulputate turpis libero, quis sodales ante volutpat non.
</div>

CodePudding user response:

  1. searching Format is breaking because p.textContent ignores html
  2. input !=="" not let running the highlighter we must remove it if empty
  3. Regular Expression ignore . you can replace . with "\." for working

const p = document.getElementById("content");
let phtml = p.innerHTML;

function search() {
    let input = document.getElementById("input").value;
    if (input !== "") {
        input = input.replace('.', "\\.");
        let regExp = new RegExp(input, "gi");
        p.innerHTML = (phtml).replace(regExp, "<span style='background-color:yellow;'>$&</span>");

    } else {
        let regExp1 = new RegExp("<span style='background-color:yellow;'>*</span>", "gi");
        p.innerHTML = (phtml).replace(regExp1, "$&");
    }
}
<nav >
    <div >
      <h1 >HTML Search Bar</h1>
      <input  type="text" placeholder="Search" aria-label="Search" id="input"
        onkeyup="search();">
    </div>
  </nav>
 <div id="content">
Phasellus consequat congue neque ac consequat. Proin ultricies risus lorem, et scelerisque lectus imperdiet vitae. Vestibulum pretium eget mauris a interdum. Donec a justo nisl. Morbi vel ante eget lectus euismod auctor. Duis interdum lobortis eros at tincidunt. Proin id egestas lectus, eu varius enim. Aliquam elit arcu, dictum at cursus non, dignissim eleifend augue. Pellentesque iaculis quis felis eu ullamcorper. Duis at sollicitudin magna, ac gravida lectus. Phasellus consectetur neque tellus, a auctor lacus fringilla eget. Proin arcu orci, auctor eu diam vitae, ultricies tincidunt dolor. Nunc sit amet magna nisl. Vivamus at nisl mattis nulla aliquam semper.
<br>
<br>
<br>
Nullam convallis leo vel magna vulputate, sed tempor nibh elementum. Cras a dui vitae odio posuere interdum. Nam interdum consequat convallis. Fusce dolor ligula, sollicitudin sed massa sed, tempus imperdiet mi. Donec vel mauris nec velit volutpat dictum. Vivamus ut erat quam. Aliquam rhoncus elit venenatis imperdiet blandit. Proin feugiat accumsan nibh quis rutrum. Quisque consequat lacinia risus id vulputate. Etiam tristique quis odio sed consequat. In in justo pharetra, dignissim metus at, sollicitudin elit. Nullam vulputate turpis libero, quis sodales ante volutpat non.
</div>

}

  • Related