【发布时间】:2013-12-22 13:50:53
【问题描述】:
我正在尝试使用 JS 将特定单词动态替换为某个 HTML 元素中的链接。我想我会使用一个简单的正则表达式:
var regEx = new RegExp('\\b'+text+'\\b', 'gi');
在上下文 div 的 innerHTML 属性上应用正则表达式替换的快速'n'nasty 方式:
context.innerHTML = context.innerHTML.replace(regEx, '<a href="#">'+text+"</a>");
这样做的问题是它也适用于图像标题,从而破坏了页面的布局。我希望它仅适用于页面的文本,如果可能的话还排除标题标签,当然还有 HTML 注释等。
所以我尝试了类似的方法,但它似乎根本不起作用:
function replaceText(context, regEx, replace) {
var childNodes = context.childNodes;
for (n in childNodes) {
console.log(childNodes[n].nodeName);
if (childNodes[n] instanceof Text) {
childNodes[n].textContent = childNodes[n].textContent.replace(regEx, replace);
} else if (childNodes[n] instanceof HTMLElement) {
replaceText(childNodes[n], regEx, replace);
console.log('Entering '+childNodes[n].nodeName);
} else {
console.log('Skipping '+childNodes[n].nodeName);
}
}
}
谁能看到我做错了什么,或者想出一个更好的解决方案?谢谢!
更新:
这是context 的内容可能是什么样子的sn-p:
<h4>Newton's Laws of Motion</h4>
<p><span class="inline_title">Law No.1</span>: <span class="caption">An object at rest will remain at rest, and an object in motion will continue to move at constant velocity, unless a net force is applied.</span></p>
<ul>Consequences: <li>Conservation of Momentum in both elastic and inelastic collisions</li>
<li>Conservation of kinetic energy in elastic collisions but not inelastic.</li>
<li>Conservation of angular momentum.</li>
</ul>
<h5>Equations</h5>
<p class="equation">ρ = mv</p>
<p>where ρ is the momentum, and m is the mass of an object moving at constant velocity v.</p>
【问题讨论】:
-
你能展示你的 HTML 吗?
-
你不应该用 RegEx 做那部分。最好缩小循环中节点的内容,仅缩小其内容,排除其子节点。
-
@PraveenJeganathan 这没什么特别的,只是一个包含一堆
和
以及图像和东西的 div... -
@Allendar 你是什么意思?
-
@Sean
context持有什么?如果你设置一个小提琴,我会容易得多。
标签: javascript html regex replace