2012-04-26 23 views
1

私は現在、ページ上の特定の文字列を置き換えるために.replace関数を使用しています。 jQueryを使用して文字列を置き換える置換と正規表現

$('body').html($('body').html().replace(regex, 'sometext')); 

ページは、もともとこのように見えたので、場合:

<div class="a">Hello</div> 

It now looks like this: 

<div class="a">sometext</div> 
私はそれを選択することはできませんので、現在の文字列がどこにあるかわからないことを考えると、私のコードは次のようになります

$('body').html($('body').html().replace())を使用せずに行う方法はありますか?

ありがとうございます!

編集:例これを使用して

<p class="last">Mac, iPhone, iPod and iPad customers within 90 days of ownership are eligible for complimentary phone support — one support incident per iPod and unlimited incidents per Mac, iPhone and iPad. <a href="/support/" onclick="s_objectID=&quot;http://www.apple.com/support/_3&quot;;return this.s_oc?this.s_oc(e):true">Online technical support</a> for Apple products is available beyond the initial 90 days.</p> 

<p class="last">Mac, <a href="#">iPhone</a>, iPod and iPad customers within 90 days of ownership are eligible for complimentary phone support — one support incident per iPod and unlimited incidents per Mac, <a href="#">iPhone</a> and iPad. <a href="/support/" onclick="s_objectID=&quot;http://www.apple.com/support/_3&quot;;return this.s_oc?this.s_oc(e):true">Online technical support</a> for Apple products is available beyond the initial 90 days.</p> 

$('body').html($('body').html().replace("iPhone", '<a href="#">iPhone</a>')); 

それはiPhone

に結果の

のようになりますように、それはiPhoneの各インスタンスを置き換えます

+0

の事、私はジェネリックとしてそれを作るしようとしているさを可能な限りそれそうどのページでも動作します。私は例を使って投稿を編集しました。 – jsllsj

+0

これを行うためのより簡潔な方法をお探しですか? –

+0

私はDOM全体を交換することなくそれを行う方法を探しています。これは、その中にjsを持つ多くのページを破るようです。 – jsllsj

答えて

3

ノードごとにDOM階層を歩くことができ、テキストノードをチェックして、個々のテキストノード内のテキストを比較することができます。それはあなたの現在のコードが引き起こす可能性のある破損のタイプを排除します。現在のコードのように、すべてのイベントハンドラを壊すことはありません。

function replaceTextInDomTree(root, searchRegEx, replace) { 
    var node = root.firstChild; 
    while(node) { 
     if (node.nodeType == 3) { 
      if (searchRegEx.test(node.nodeValue)) { 
       // we do the test first to avoid setting 
       // nodeValue when there's no change 
       // to perhaps save the browser some layout time 
       // since we'd be operating on every single text node 
       node.nodeValue = node.nodeValue.replace(searchRegEx, replace); 
      } 
     } 
     if (node.hasChildNodes()) { 
      // go down into the children 
      node = node.firstChild; 
     } else { 
      while (!node.nextSibling) { 
       node = node.parentNode; 
       if (node == root) { 
        return; 
       } 
      } 
      node = node.nextSibling; 
     } 
    } 
} 

注:これはのみで連続したテキストブロック内のテキストを置き換えます

1)

FYI、ここであなたがやりたいだろう、私はa different answerのために書いたさまざまな機能の変更がありますその中にHTMLタグはありません。

2)あなたは、同じテキストノードで複数の置き換えをしたい場合は、gフラグあなたが渡す正規表現を入れていることを確認してください。

+0

これはこれを行う唯一の方法のようです。ありがとう! – jsllsj

+0

@jsllsj - 私はあなたが望むことをする必要がある特定のツリーウォーキング関数を追加しました。 – jfriend00

+0

@ jfriendのコード[こちら](http://jsfiddle.net/kbj2j/4/)の作業バージョン。 "iPhone"の出現を置き換えますが、javascript関数内のテキストは置き換えません。 –

関連する問題