首页 > 解决方案 > 用自定义 html 替换文本

问题描述

我想在我的聊天应用程序中显示短信对话。

我的情况:当用户在搜索框中搜索某些文本时,包含 searchText 的消息将是红色样式。例子:

user search: "div"

// messageText = "abc <div>all is text</div>" (searching in plain text here);
// htmlText = "abc &lt;div&gt;all is text&lt;/div&gt;";
// OUTPUT MUST BE: "abc &lt;<span style='color: red'>custom</span>&gt;string &lt;<span style='color: red'>custom</span>&gt"

这是我的代码:

const origin = "abc <div>all is text </div>"; // text input
const str = "abc &lt;div&gt;all is text &lt;/div&gt;"; // after sanitize

const element = document.createElement("div");
element.innerHTML = str;
for (let node of element.childNodes) {
  // I want replace "div" text with my custom html
  node.textContent = node.textContent.replace(/div/gi, "<span style='color: red'>custom</span>");
}

const result = element.innerHTML;
console.log(result);

这是result输出

输出

abc &lt;&lt;span style='color: red'&gt;custom&lt;/span&gt;&gt;string &lt;/&lt;span style='color: red'&gt;custom&lt;/span&gt;&gt;

预计

abc &lt;<span style='color: red'>custom</span>&gt;string &lt;<span style='color: red'>custom</span>&gt;

你能帮我吗,谢谢你的帮助。

标签: javascript

解决方案


node.textContent = ...通过转义您传递给它的任何内容,将产生有效的文本。

如果您想插入 HTML,请使用node.innerHTML

node.innerHTML = node.textContent.replace(/div/gi, "<span style='color: red'>custom</span>");

编辑 我意识到你的问题比这更复杂。您首先需要对文本中的 HTML 进行转义,然后替换div为要插入的 HTML,最后用于inneHTML应用​​结果。

Edit2 更新您的问题后,我了解您想在文本输入中搜索/突出显示某些内容。编辑代码来做到这一点

根据这个答案

function escapeHtml(unsafe) {
  return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

function highlightSearch(node, query) {
  //Within node, highlight matched text (using replacement "$&")
  //highlight done by surrounding found text with a <span>
  let txt = node.textContent;                 //Get inner text
  console.log('raw text:', txt);
  txt = escapeHtml(txt);                      //Escape text with HTML entities
  console.log('html text:', txt);
  //Search and replace ("$&" = whole matched substring)
  txt = txt.replaceAll(query, "<span style='color: red'>$&</span>");
  console.log('highlighted:', txt);
  //Show result
  node.innerHTML = txt;         //<-- innerHTML
}

document.querySelector('#btn-search').addEventListener('click', e => {
  //Read query
  let q = document.querySelector('#search-query').value;
  console.log('raw query:', q);
  //Make search query html
  q = escapeHtml(q);
  console.log('html query:', q);
  //Perform search/highlight
  document.querySelectorAll('.search-in').forEach(node => {
    highlightSearch(node, q);
  });
});
button {
  margin-top: 1em;
}
<p class="search-in">abc &lt;div&gt;all is text &lt;/div&gt;</p>
<p class="search-in">a &lt;div> is not a &lt;/div>. but I can find 2 &lt;div></p>
<input type="search" id="search-query" value="<div>" />
<button id="btn-search">Search</button>


推荐阅读