gpt4 book ai didi

javascript - 如何使用 JavaScript 将部分文本包装在节点中

转载 作者:IT王子 更新时间:2023-10-29 03:05:31 26 4
gpt4 key购买 nike

我有一个具有挑战性的问题要解决。我正在编写一个将正则表达式作为输入的脚本。然后,此脚本会在文档中查找此正则表达式的所有匹配项,并将每个匹配项包装在其自己的 元素中。困难的部分是文本是格式化的 html 文档,因此我的脚本需要在 DOM 中导航并同时在多个文本节点上应用正则表达式,同时确定在需要时必须在何处拆分文本节点。

例如,使用正则表达式捕获以大写字母开头并以句点结尾的完整句子,此文档:

<p>
<b>HTML</b> is a language used to make <b>websites.</b>
It was developed by <i>CERN</i> employees in the early 90s.
<p>

会变成这样:

<p>
<span><b>HTML</b> is a language used to make <b>websites.</b></span>
<span>It was developed by <i>CERN</i> employees in the early 90s.</span>
<p>

然后脚本返回所有创建的 span 的列表。

我已经有一些代码可以找到所有文本节点并将它们连同它们在整个文档中的位置和深度一起存储在一个列表中。你真的不需要理解那些代码来帮助我,它的递归结构可能有点令人困惑。 我不确定该怎么做的第一部分是弄清楚哪些元素应该包含在范围内。

function SmartNode(node, depth, start) {
this.node = node;
this.depth = depth;
this.start = start;
}


function findTextNodes(node, depth, start) {
var list = [];
var start = start || 0;
depth = (typeof depth !== "undefined" ? depth : -1);

if(node.nodeType === Node.TEXT_NODE) {
list.push(new SmartNode(node, depth, start));
} else {
for(var i=0; i < node.childNodes.length; ++i) {
list = list.concat(findTextNodes(node.childNodes[i], depth+1, start));
if(list.length) start += list[list.length-1].node.nodeValue.length;
}
}

return list;
}

我想我会从所有文档中生成一个字符串,通过它运行正则表达式并使用列表来查找哪些节点对应于女巫正则表达式匹配,然后相应地拆分文本节点。

但是当我有这样的文档时,问题就来了:

<p>
This program is <a href="beta.html">not stable yet. Do not use this in production yet.</a>
</p>

有一个句子开始于 <a> 之外标签但在其中结束。现在我不希望脚本将该链接分成两个标签。在更复杂的文档中,它可能会破坏页面。代码可以将两个句子包装在一起:

<p>
<span>This program is <a href="beta.html">not stable yet. Do not use this in production yet.</a></span>
</p>

或者只是将每个部分包装在它自己的元素中:

<p>
<span>This program is </span>
<a href="beta.html">
<span>not stable yet.</span>
<span>Do not use this in production yet.</span>
</a>
</p>

可以有一个参数来指定它应该做什么。我只是不确定如何确定何时将发生不可能的切割,以及如何从中恢复。

另一个问题是当我在像这样的子元素中有空格时:

<p>This is a <b>sentence. </b></p>

从技术上讲,正则表达式匹配将在句点之后结束,在 <b> 结束之前标签。然而,将空格视为匹配的一部分并像这样包装它会更好:

<p><span>This is a <b>sentence. </b></span></p>

比这个:

<p><span>This is a </span><b><span>sentence.</span> </b></p>

但这是一个小问题。毕竟,我可以只允许在正则表达式中包含额外的空白。

我知道这听起来像是一个“帮我做”的问题,而不是我们每天在 SO 上看到的那种快速问题,但我已经坚持了一段时间,这是一个开放的问题-我正在处理的源库。解决这个问题是最后一个障碍。如果您认为另一个 SE 站点最适合回答这个问题,请重定向我。

最佳答案

这里有两种方法可以解决这个问题。

我不知道以下内容是否完全符合您的需求。这是一个足够简单的问题解决方案,但至少它不使用 RegEx 来操作 HTML 标记。它对原始文本执行模式匹配,然后使用 DOM 来操作内容。


第一种方法

这种方法只创建一个 <span>标记每个匹配项,利用一些不太常见的浏览器 API。
(看demo下面这个方法的主要问题,如果不确定就用第二种方法)

Range 类代表一个文本片段。它有一个 surroundContents 允许您将范围包装在元素中的函数。除了它有一个警告:

This method is nearly equivalent to newNode.appendChild(range.extractContents()); range.insertNode(newNode). After surrounding, the boundary points of the range include newNode.

An exception will be thrown, however, if the Range splits a non-Text node with only one of its boundary points. That is, unlike the alternative above, if there are partially selected nodes, they will not be cloned and instead the operation will fail.

好吧,MDN 中提供了解决方法,所以一切都很好。

所以这是一个算法:

  • 列出 Text节点并在文本中保留它们的起始索引
  • 连接这些节点的值以获得 text
  • 在文本中查找匹配项,对于每个匹配项:

    • 找到匹配的开始和结束节点,将节点的开始索引与匹配位置进行比较
    • 创建 Range在比赛中
    • 使用上面的技巧让浏览器完成脏活
    • 自上次操作更改 DOM 后重建节点列表

这是我的演示实现:

function highlight(element, regex) {
var document = element.ownerDocument;

var getNodes = function() {
var nodes = [],
offset = 0,
node,
nodeIterator = document.createNodeIterator(element, NodeFilter.SHOW_TEXT, null, false);

while (node = nodeIterator.nextNode()) {
nodes.push({
textNode: node,
start: offset,
length: node.nodeValue.length
});
offset += node.nodeValue.length
}
return nodes;
}

var nodes = getNodes(nodes);
if (!nodes.length)
return;

var text = "";
for (var i = 0; i < nodes.length; ++i)
text += nodes[i].textNode.nodeValue;

var match;
while (match = regex.exec(text)) {
// Prevent empty matches causing infinite loops
if (!match[0].length)
{
regex.lastIndex++;
continue;
}

// Find the start and end text node
var startNode = null, endNode = null;
for (i = 0; i < nodes.length; ++i) {
var node = nodes[i];

if (node.start + node.length <= match.index)
continue;

if (!startNode)
startNode = node;

if (node.start + node.length >= match.index + match[0].length)
{
endNode = node;
break;
}
}

var range = document.createRange();
range.setStart(startNode.textNode, match.index - startNode.start);
range.setEnd(endNode.textNode, match.index + match[0].length - endNode.start);

var spanNode = document.createElement("span");
spanNode.className = "highlight";

spanNode.appendChild(range.extractContents());
range.insertNode(spanNode);

nodes = getNodes();
}
}

// Test code
var testDiv = document.getElementById("test-cases");
var originalHtml = testDiv.innerHTML;
function test() {
testDiv.innerHTML = originalHtml;
try {
var regex = new RegExp(document.getElementById("regex").value, "g");
highlight(testDiv, regex);
}
catch(e) {
testDiv.innerText = e;
}
}
document.getElementById("runBtn").onclick = test;
test();
.highlight {
background-color: yellow;
border: 1px solid orange;
border-radius: 5px;
}

.section {
border: 1px solid gray;
padding: 10px;
margin: 10px;
}
<form class="section">
RegEx: <input id="regex" type="text" value="[A-Z].*?\." /> <button id="runBtn">Highlight</button>
</form>

<div id="test-cases" class="section">
<div>foo bar baz</div>
<p>
<b>HTML</b> is a language used to make <b>websites.</b>
It was developed by <i>CERN</i> employees in the early 90s.
<p>
<p>
This program is <a href="beta.html">not stable yet. Do not use this in production yet.</a>
</p>
<div>foo bar baz</div>
</div>

好吧,那是惰性方法,不幸的是,它在某些情况下不起作用。如果您突出显示内联元素,它会很好地工作,但由于 extractContents 的以下属性,当沿途有 block 元素时会中断功能:

Partially selected nodes are cloned to include the parent tags necessary to make the document fragment valid.

这很糟糕。它只会复制 block 级节点。使用 baz\s+HTML 尝试之前的演示正则表达式,如果你想看看它是如何中断的。


第二种方法

此方法迭代匹配节点,创建 <span>一路上的标签。

整个算法很简单,因为它只是将每个匹配节点包装在自己的 <span> 中。 .但这意味着我们必须处理部分匹配的文本节点,这需要更多的努力。

如果一个文本节点部分匹配,它将与 splitText 分开功能:

After the split, the current node contains all the content up to the specified offset point, and a newly created node of the same type contains the remaining text. The newly created node is returned to the caller.

function highlight(element, regex) {
var document = element.ownerDocument;

var nodes = [],
text = "",
node,
nodeIterator = document.createNodeIterator(element, NodeFilter.SHOW_TEXT, null, false);

while (node = nodeIterator.nextNode()) {
nodes.push({
textNode: node,
start: text.length
});
text += node.nodeValue
}

if (!nodes.length)
return;

var match;
while (match = regex.exec(text)) {
var matchLength = match[0].length;

// Prevent empty matches causing infinite loops
if (!matchLength)
{
regex.lastIndex++;
continue;
}

for (var i = 0; i < nodes.length; ++i) {
node = nodes[i];
var nodeLength = node.textNode.nodeValue.length;

// Skip nodes before the match
if (node.start + nodeLength <= match.index)
continue;

// Break after the match
if (node.start >= match.index + matchLength)
break;

// Split the start node if required
if (node.start < match.index) {
nodes.splice(i + 1, 0, {
textNode: node.textNode.splitText(match.index - node.start),
start: match.index
});
continue;
}

// Split the end node if required
if (node.start + nodeLength > match.index + matchLength) {
nodes.splice(i + 1, 0, {
textNode: node.textNode.splitText(match.index + matchLength - node.start),
start: match.index + matchLength
});
}

// Highlight the current node
var spanNode = document.createElement("span");
spanNode.className = "highlight";

node.textNode.parentNode.replaceChild(spanNode, node.textNode);
spanNode.appendChild(node.textNode);
}
}
}

// Test code
var testDiv = document.getElementById("test-cases");
var originalHtml = testDiv.innerHTML;
function test() {
testDiv.innerHTML = originalHtml;
try {
var regex = new RegExp(document.getElementById("regex").value, "g");
highlight(testDiv, regex);
}
catch(e) {
testDiv.innerText = e;
}
}
document.getElementById("runBtn").onclick = test;
test();
.highlight {
background-color: yellow;
}

.section {
border: 1px solid gray;
padding: 10px;
margin: 10px;
}
<form class="section">
RegEx: <input id="regex" type="text" value="[A-Z].*?\." /> <button id="runBtn">Highlight</button>
</form>

<div id="test-cases" class="section">
<div>foo bar baz</div>
<p>
<b>HTML</b> is a language used to make <b>websites.</b>
It was developed by <i>CERN</i> employees in the early 90s.
<p>
<p>
This program is <a href="beta.html">not stable yet. Do not use this in production yet.</a>
</p>
<div>foo bar baz</div>
</div>

我希望这对于大多数情况应该足够好了。如果你需要最小化 <span> 的数量标记它可以通过扩展这个函数来完成,但我现在想保持简单。

关于javascript - 如何使用 JavaScript 将部分文本包装在节点中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31275446/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com