在某个单词

时间:2016-05-19 21:09:53

标签: javascript jquery regex

标题几乎解释了它。我希望在JavaScript中每次出现特定单词(例如:'the')后添加用户定义的单词或短语(例如:'great')。所以,每次'the'出现在HTML的文本中(等等等等等等),JavaScript会注入'最大'(等等等等等等等等等)。我试图用正则表达式来解决这个问题,但是没有将它直接添加到HTML中。

4 个答案:

答案 0 :(得分:0)

以下是一些能够满足您需求的代码。请注意,它不会改变“橙色”,因为它具有敏感性。另请注意,它不会更改警告的“橙色”,因为它存在于脚本元素中。

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>

答案 1 :(得分:0)

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

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

在这里,\b代表单词边界(空格,句号等)并避免将“其他”替换为“其他最大r”,“the”周围的括号允许您选择它(使用它)在替换中,使用$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>

答案 2 :(得分: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>

答案 3 :(得分:0)

要动态完成这项工作,一种方法是发明我们自己的String.prototype.affix()方法。这个新方法将按照你想要的方式执行,如果最后一个参数是true,它会将提供的字符串附加到结尾(第二个参数)到结尾,如果false附加到搜索到的子句的前面string(第一个参数)。我已将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));