【发布时间】: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>
因为我必须保留<tag2>,所以我必须复制此标签以在</marker> 之前将其关闭并在!!!! 之前重新打开。
是否已经存在将 HTML 代码添加到其他 HTML 文本的方法?
【问题讨论】:
-
我猜的方法是: 1. 将 HTML 解析为 DOM 2. 根据您的数据选择元素/节点并相应地替换它们(即 textnode "Hello" 成为元素
Hello marker>,元素 被包裹在 中)肯定不是一件容易的事。
标签: javascript html node.js replace character