gpt4 book ai didi

javascript - 如何选择文本中的
block ?

转载 作者:行者123 更新时间:2023-12-03 05:55:48 25 4
gpt4 key购买 nike

我有一个由两个 <div> 组成的文本里面一个<body>另存为raw_text如下:

var raw_text = "<body><div>This is the 'div' text that I don't want.</div> <div>This is the 'div' text that I want to print.</div></body>";

我需要一个脚本来仅在屏幕上打印 <div>存在于包含特定字符串的原始文本中。

如果想要的字符串是:

var x = "that I want";

脚本应该采用:

<div>This is the 'div' text that I want to print.</div>

输出应该是:

This is the 'div' text that I want to print.

最佳答案

这是正确的方法:

  1. 使用 DOM 解析器
  2. 迭代文本节点
  3. 检查它们是否包含所需的字符串

var html = "<body><div>This is the 'div' text that I don't want.</div> <div>This is the 'div' text that I want to print.</div></body>";
var x = "that I want";
var doc = new DOMParser().parseFromString(html, 'text/html');
var it = doc.createNodeIterator(doc.body, NodeFilter.SHOW_TEXT);
var node;
while (node = it.nextNode()) if(node.nodeValue.includes(x)) {
console.log(node.nodeValue);
break;
}

关于javascript - 如何选择文本中的 <div> block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39934963/

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