簡體   English   中英

Javascript / Jquery +在內部html內容中替換單引號和雙引號

[英]Javascript / Jquery+ Replace single and double quotes in a inner html content

假設我有一個DIV,如下所示。

<div id="mydiv">
    <p class="abc">some text here</p>
    <p class="xyz"><img src="img.jpg" title="my img"/> some "double quoted text" here</p>
</div>

我閱讀了div的內部html。

var originalcontent = $("mydiv").html();

現在,我只需要替換文本的雙引號,而不是標簽屬性。 所以我的輸出應該如下。

var myoutput = '<p class="abc">some text here</p><p class="xyz"><img src="img.jpg" title="my img"/> some &quot;double quoted text&quot; here</p>'

請給我一個解決方案。 謝謝!

嘗試這個:

function replace_text(node){ 
  node = node || document.getElementById('mydiv'); // Change 'mydiv' if you need 

  var children = node.childNodes;
  var i = 0;

  while(node = children[i]){ // While-loop

    if (node.nodeType == 3){ // Some text, replace
        if (node.textContent) { // Not IE (IE's equivalent to textContent is nodeValue)
            node.textContent = node.textContent.replace(/"/g, '&quot;');
        }
        else { // IE
            node.nodeValue = node.nodeValue.replace(/"/g, '&quot;');
        }
    } else { // not text, take step further
      replace_text(node); 
    } 
    i++; 
  } 

} // While-loop


// Don't forget to call function
replace_text();

使用jQuery,您可以執行以下操作:

    String.prototype.replaceAll = function(stringToFind,stringToReplace){
    var temp = this;
    var index = temp.indexOf(stringToFind);
        while(index != -1){
            temp = temp.replace(stringToFind,stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
   };
    $(function(){                     

            $("#mydiv").children().each(function(){
                 var text=$(this).text(); 
                 text=text.replaceAll("\"","&quot;"); 
                 //alert(text);
                 $(this).text(text); 
             });
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM