javascript - 如何在 Javascript 中获取 HTML 标记内的内容(仅)到单级?
问题描述
TLDR: Need javascript solution to this question Search and replace HTML Text, not tags
我经历了很多回答说不要使用RegeX,但没有人对此给出确切的解决方案。我想遍历页面上的每个 DOM 元素。根据其文本查找一个单词并在 word 的相同位置替换一个 HTML。
$(document).ready(function(){
function isJson(item) {
item = typeof item !== "string"
? JSON.stringify(item)
: item;
try {
item = JSON.parse(item);
} catch (e) {
return false;
}
if (typeof item === "object" && item !== null) {
return true;
}
return false;
}
function loop(elements, words) {
elements.each(function(){
element = $(this);
var text = element.html();
for (k in words) {
if(isJson(words[k])){
defObj = JSON.parse(words[k]);
for (var j = defObj["data"].length - 1; j >= 0; j--) {
if (defObj["data"][j]["definition"]) {
liText = (defObj["data"][j]["wordtype"] ? defObj["data"][j]["wordtype"] : defObj["data"][j]["partOfSpeech"]) + "; "+ defObj["data"][j]["definition"];
}else{
liText = defObj["data"][j]["translatedText"];
}
}
}else{
liText = words[k];
}
li = '<li>'+liText+'</li>';
ol = '<ol style="padding: 15px !important; padding-right: 0px !important; margin: 0 auto !important;">'+li+'</ol>';
var regex = new RegExp('(\\b)'+k+'(\\b)', 'ig');
// replace the matched word with the ol list created above.
text = text.replace(regex, ol);
}
if (element.html() !== text) {
element.html(text);
}
})
}
function getElements(el) {
return $(el).withinviewport();
}
chrome.storage.sync.get(null, function(result) {
//result is an object literal with words as key and its meaning as json string
if (result) {
loop($("li"), result);
loop($("h5"), result);
loop($("h6"), result);
}
});
});
到目前为止,上面的代码做得很好。但它错过了以下情况,以sett关键字为例,我不想匹配以下情况,但我的正则表达式也匹配这些。
1. <h5 title="this settle line should not match"> This settle line should match </h5>
2. <li> this settle line should match <div> this settle line should not match </div> </li>
3. <li> <a href="abc"> this settle line should not match </a> this settle line should match </li>
4. <h6> this settle line should match
<div>
something random without settle word, so should not match
<h6> this settle line should also not match </h6>
</div>
</h6>
如果我想用文本替换这些情况可以避免。但是对于 HTML,如果标签中的某些内容匹配,它会破坏布局。我从2年开始就面临这个问题,请帮忙。我愿意接受任何解决方案。
解决方案
我的回答是指问题的第一部分,“在示例中的 javascript 中执行与 python 中相同的操作:搜索和替换 HTML 文本,而不是标签”
在此基础上,您应该弄清楚如何开发一个解决方案来更改标签内容,如问题的第 2 部分所述。
代码有效,但它只是一个概念,需要重构。
// the data:
var input = '<!DOCTYPE html>\
<html>\
<head>\
<title>Hello HTML</title>\
</head>\
<body>\
<a href="#">abc</a>\
<p>Hello 1</p>\
<p>Hello 2</p>\
<p>Hello 3</p>\
<p>Hello 4</p>\
</body>\
</html>';
function string2xml(text) {
try {
var xml = null;
if (window.DOMParser) {
var parser = new DOMParser();
xml = parser.parseFromString(text, 'text/xml');
var foundErr = xml.getElementsByTagName('parsererror');
if (!foundErr || !foundErr.length || !foundErr[0].childNodes.length) {
return xml;
}
return null;
}
} catch (e) {
;
}
}
// xml object input data:
var xmldoc = string2xml(input);
var out='';
out += '<!DOCTYPE html><html>';
// the head nodes:
out += xmldoc.getElementsByTagName('head')[0].outerHTML;
out += '<body>\n';
// the body nodes:
var nodes=xmldoc.getElementsByTagName('body')[0].children;
for (var i = 0; i < nodes.length; i++) {
if(nodes.item(i).nodeName == 'p') {
regex=/^[^4]*$/;
out += '<p>'+(nodes.item(i).innerHTML).replace(regex,"replaced")+'</p>\n';
}
else {
out += nodes.item(i).outerHTML+'\n';
}
}
out += '</body></html>';
// the output data:
console.log(out);
推荐阅读
- google-data-studio - Google Data Studio 在自定义日期过滤器默认范围中指示昨天时忽略周六和周日
- go - `go test` 只打印“打开:没有这样的文件或目录”
- swift - 如何创建底部两个角为圆角的自定义 UINavigationBar?
- javascript - JS:拖放 DataTransfer 对象在 Safari 上不起作用。选择?
- php - 未捕获的 TypeError:ctlLayers.addOverLay 不是函数
- c# - 上传图像以训练自定义视觉时出现未经授权的异常
- reactjs - 为什么函数式组件会渲染两次?
- java - 为什么以下代码不能根据输入日期生成正确的输出
- r - 在 R 中跨列应用函数列表以填写表格
- c - 以相反的顺序打印字符串数组中的字符串