【问题标题】:Add HTML tags to HTML text?将 HTML 标记添加到 HTML 文本?
【发布时间】:2021-08-15 13:51:50
【问题描述】:

我正在使用它们的字符索引将 HTML 标记 添加到文档中的特定文本片段,例如具有以下元素:

{
    "text": "Hello",
    "start": 0,
    "end": 5
}

还有这样的文字:Hello world,我将有以下文字:<marker>Hello</marker> world

var text = Hello world
var new_text = ""
for (var i = 0; i < Array.from(text).length; i++) {
   char_text_array.push({ char: Array.from(text)[i] });
}

char_text_array.forEach(char => {
   //computing some operation buffering the piece of text contained in the new HTML marker and adding the field "last" to last character of the element 'Hello' (o)
   var match = ... //True if the character is part of an element which has to be sorrounded with an HTML tag, otherwise False
   if ("last" in char && buffer != "" and match) {
       new_text += `<marker>${buffer}</marker>`;
       buffer = "";
   }
   elif ("last" not in char && match) {
       buffer = += char.char;
   }
   else{
       new_text += char.char
   }
});

但是如果文本已经是HTML,比如:

var text = "<tag1>Hello <tag2>world!!!!</tag2></tag1>"

我想在Hello world 周围加上一个标记而不删除其他标签。由于临时避免了 HTML 标签的算法,我能够找到这个结果:

{
    "text": "Hello <tag2>world",
    "start": 6,
    "end": 23
}

但是如何将标记放在Hello 之前和world 之后?结果是:

<tag1><marker>Hello <tag2>world</marker>!!!!</tag2></tag1>

但很明显,我破坏了标签的正确顺序,我认为应该是:

<tag1><marker>Hello <tag2>world</tag2></marker><tag2>!!!!</tag2></tag1>

因为我必须保留&lt;tag2&gt;,所以我必须复制此标签以在&lt;/marker&gt; 之前将其关闭并在!!!! 之前重新打开。

是否已经存在将 HTML 代码添加到其他 HTML 文本的方法?

【问题讨论】:

  • 我猜的方法是: 1. 将 HTML 解析为 DOM 2. 根据您的数据选择元素/节点并相应地替换它们(即 textnode "Hello" 成为元素 Hello marker>,元素 被包裹在 中)肯定不是一件容易的事。

标签: javascript html node.js replace character


【解决方案1】:

为什么不使用浏览器的本地解析器的帮助?创建一个 HTML 元素,并将您的 HTML 文本附加到其中,而不是获取包含您的文本的任何需要突出显示的 HTML 元素。

let fragment = document.createElement('div');
fragment.innerHTML = "<tag1>Hello <tag2>world!!!!</tag2></tag1>";

// declare a function, which will return any element by XPath
fragment.getElementByXpath = function (path) {
  return document.evaluate(path, fragment, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
// getting the element containing the string Hello, or whichever you need
fragment.getElementByXpath('//*[contains(string(), Hello)]')

如果元素与容器不同,则可以用marker 包裹父节点。 你也可以简单地在你的代码片段上使用parentNode.getElementsByTagName('*'),这将返回一个包含所有子元素的HTML collection。如果 length 为 0,则表示您没有内部标签。 如果有帮助,请告诉我。

【讨论】:

    猜你喜欢
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多