2016-05-19 9 views
0

タイトルはかなり説明しています。私は、JavaScriptで特定の単語(例: 'the')が出現するたびに、ユーザー定義の単語または語句(例: 'great')を追加したいと考えています。したがって、HTMLのテキストに「the」と表示されるたびに、JavaScriptが「最大」(blah blah blah、blah blah)を挿入します。私はこれを正規表現を使って把握しようとしていましたが、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

ここでは、あなたがしたいことをするいくつかのコードがあります。それは感覚的なので "オレンジ"を変更しないことに注意してください。スクリプト要素に存在するため、アラートされた「オレンジ」は変更されません。

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ならば、最後に添え字(2番目の引数)に添え字を付け、検索された部分文字列(最初の引数)の先頭に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));

関連する問題