Javascript如何在使用正则表达式选择单词时过滤掉HTML标记



注意:

我不使用regex解析HTML,
这里我只将其用于纯文本
只是它超越了纯文本,影响了其他html标签

为什么每个人都说我应该使用DOM而不是正则表达式?CCD_ 2显然不能基于单词数组来选择网页上的所有单词。

在我使用document.createTreeWalker()过滤所有文本标签之前,它太复杂了,导致了更多的错误。所以我想用简单的regex来代替。你有更好的方法吗?

我认为只要"过滤掉里面的所有文本"<gt"'使用非常简单的regex语法,它不会工作吗?为什么让它变得如此复杂?


我需要根据单词数组从页面中选择单词,并将单词包裹在"span"标记周围(保留原始HTML标记)。

我的代码的问题是它也替换了HTML标记的属性值。

我需要正则表达式来过滤HTML标签并选择单词。

我在正则表达式中添加了一个条件:(^<.*>),但它不起作用,破坏了我的代码。

怎么办?


我的代码:

代码错误:<div id="text">不应该被包裹在SPAN标签周围

<!DOCTYPE html>
<html>
<head>
<style>span{background:#ccc;}</style>
<script>
//wrap span tags for all words
function add_span(word_array, element_) {
for (let i = 0; i < word_array.length; i++) {
var reg_str = "([\s.?,"';:!()\[\]{}<>/])";  //  + "^(<.*>)"
var reg = new RegExp(reg_str + "(" + word_array[i] + ")" + reg_str, 'g');
element_ = element_.replace(reg, '$1<span>$2</span>$3');
}
return element_;
}
window.onload = function(){
console.log(document.body.innerText);
// word array
var word_array = ['is', 'test', 'testis', 'istest', 'text']
var text_html = add_span(word_array, document.body.innerHTML);
document.body.innerHTML = text_html;
console.log(text_html);
}
</script>
</head>
<body>
<div id="text"><!--Error: The class attribute value here should not be wrapped around the SPAN tag-->
is test testis istest,
is[test]testis{istest}testis(istest)testis istest
</div>
</body></html>

我玩得很开心,也学到了一些东西。如果您愿意,可以用TreeWalker替换遍历实现。我添加了一个嵌套的div#text2来演示它如何在任意树深度下工作。我试图保持您使用的通用方法,但需要对正则表达式进行一些修改并添加树遍历。希望这能有所帮助!

function traverse(tree) {
const queue = [tree];
while (queue.length) {
const node = queue.shift();
if (node.nodeType === Node.TEXT_NODE) {
const textContent = node.textContent.trim();
if (textContent) {
const textContentWithSpans = textContent
.replaceAll(/b(is|test|testis|istest|text)b/g, '<span>$&</span>');

const template = document.createElement('template');
template.innerHTML = textContentWithSpans;
const fragment = template.content;

node.parentNode.replaceChild(fragment, node);
}
}

for (let child of node.childNodes) {
queue.push(child);
}
}
}
traverse(document.getElementById('demo-wrapper'));
<div id="demo-wrapper">
<div id="text">
is test testis istest,
is[test]testis{istest}testis(istest)testis istest
<div id="text2">
foo bar test istest
</div>
</div>
</div>

最新更新