2016-05-19 36 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));

相關問題