gpt4 book ai didi

javascript - 解开 HTML 标签,仅保留第一级

转载 作者:行者123 更新时间:2023-12-03 03:22:56 27 4
gpt4 key购买 nike

我有这段文字

"Welcome to my city. <span><span><span>Hello</span> my</span> good</span> friend"

使用 jQuery(或 javascript),我想解开所有 span 标签,只保留第一级,我的意思是,理想的输出将是:

"Welcome to my city. <span>Hello my good</span> friend"

提前谢谢您。

最佳答案

您可以通过将 HTML 注入(inject)到元素中来解析 HTML,然后抓取其子节点,按原样输出文本节点,并通过读取 .textContent 并替换.innerHTML 与此。

function topLevelNodesOnly(html) {
let div = document.createElement('div');
div.innerHTML = html;

let out = '';
// using [...someVar] converts array-like things into real arrays
[...div.childNodes].forEach((node) => {
// if the node is a text node, add it's text to the output string
if (node.nodeType === 3) {
out += node.wholeText;
} else {
// if it is anything else, replace it's contents with the text
// of it's contents
node.innerHTML = node.textContent;
// add the html that generated to the output
out += node.outerHTML;
}
});

return out;
}

console.log(topLevelNodesOnly(`Welcome to my city. <span class="hello"><span><span>Hello</span> my</span> good</span> friend`));

关于javascript - 解开 HTML 标签,仅保留第一级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46486856/

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