2016-05-19 34 views
0

标题可以很好地解释它。我想在JavaScript中每次出现特定单词(例如:'the')后添加用户定义的单词或短语(例如:'great')。所以每当'the'出现在HTML的文本中(等等等等),JavaScript就会注入'最大'(等等等等等等)。我试图用正则表达式来解决这个问题,但没有直接将它添加到HTML中。在某个单词的每个实例之后搜索HTML和短语

回答

0

事实上,正则表达式是完美的做到这一点。您可以使用String.replace()函数替换文本:

someString.replace(/\b(the)\b/ig, "$1 greatest"); 

这里,\b代表单词边界(空间,时间等),并避免与“行吟诗人最大的R”,周围的括号“代替“其他” “允许您选择它(在更换中使用它,通过使用$1)。然后,ig是使您的正则表达式不区分大小写和全局(标识多次出现)的标志。

但这不是大部分工作需要完成的地方。替换元素的文本可能会干扰实际的HTML。为了避免这种情况,你可以递归函数只定位文本节点:

document.getElementById('btn').addEventListener('click', function() { 
 
    doReplace(/\b(the)\b/ig, "$1 greatest", document.body); 
 
    this.style.visibility = 'hidden'; 
 
}); 
 

 
function doReplace(search, replacement, element) { 
 
    if (element.nodeType == 3) { // if the element is a text node, replace the content 
 
    element.nodeValue = element.nodeValue.replace(search, replacement); 
 
    } else { // otherwise, apply this function to all children 
 
    var children = element.childNodes; 
 
    for (var i = 0; i < children.length; i++) { 
 
     doReplace(search, replacement, children[i]); 
 
    } 
 
    } 
 
}
<button id="btn">Add "greatest"!</button> 
 
<h1>The pie was cold</h1> 
 
<p>I was at the restaurant the other day, and the waiter took my order. The problem? My pie was cold!</p>

+0

这正是我一直在寻找,谢谢! – Zuse

0

这是一些代码,将做你想做的。请注意,它不会更改“The orange”,因为它是大小写敏感的。还要注意,它不会更改提醒的“橙色”,因为它存在于脚本元素中。

function getTextNodesThatContain(text) { 
 
    var textNodes = $(document).find(":not(iframe, script, style)") 
 
     .contents().filter( 
 
      function() { 
 
      return this.nodeType == 3 
 
      && this.textContent.indexOf(text) > -1; 
 
    }); 
 
    return textNodes; 
 
}; 
 

 
$(document).ready(function() { 
 
getTextNodesThatContain("the").each(function(ind, item) { 
 
    item.nodeValue = item.nodeValue.replace("the", "the greatest"); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
This is the apple. 
 
<div> this is the orange. </div> 
 
<script> 
 
    function alertme() { 
 
    alert("the orange"); 
 
    } 
 
    </script> 
 
<a href="javascript:alertme()">The orange</a>

0

我的建议是使用TreeWalker搜索身体内的所有文本节点:

function replaceTextInPage(el, txtMatch, txtToReplace) { 
 
    txtToReplace = (txtToReplace.length > 0) ? ' ' + txtToReplace : ''; 
 
    var walk = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null, false); 
 
    while (n = walk.nextNode()) { 
 
    if (n.textContent.trim().length > 0) { 
 
     n.textContent = n.textContent.replace(new RegExp(txtMatch, "gi"), txtMatch + txtToReplace); 
 
    } 
 
    } 
 
} 
 

 
window.onload = function() { 
 
    document.getElementById('btn').addEventListener('click', function() { 
 
    replaceTextInPage(document.body, document.getElementById('txtToFind').value, document.getElementById('txtToAdd').value) 
 
    }, false); 
 
}
<button id="btn">Replace string</button><br/> 
 
Text to search: <input id="txtToFind" type="text" value="the"><br/> 
 
Text to add at the end: <input id="txtToAdd" type="text" value="greatest"><br/> 
 
<div style="width: 100%;height: 100px;">It seems to only remove <span style="color: red;">the</span> first occurrence of abc in <span style="color: red;">the</span> string above. How can I replace all occurrences of it?</div>

+0

我从来没有听说过treewalker。这是我必须考虑的事情。 – Zuse

0

要动态地完成这项工作, y正在发明我们自己的String.prototype.affix()方法。这个新方法将做你想做的事情,如果最后一个参数是true它附加提供的字符串来粘贴(第二个参数)到最后,如果false到搜索到的一段子字符串(第一个参数)的前面。我已将true作为默认值分配给最后一个参数。

String.prototype.affix = function(s,a,b = true){ 
 
    var r = new RegExp(s,"g"); 
 
    return b ? this.replace(r,"$&" + " " + a) 
 
      : this.replace(r,a + " " + "$&"); 
 
} 
 

 
console.log("this is the book and the author is him".affix("the", "greatest",true));

相关问题