简体   繁体   中英

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

Let's say I have a DIV as below.

<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>

I read the inner html of the div.

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

Now I need to replace double quotes for the texts only but not for the tag attributes. So my output should be as below.

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>'

Can you suggest me a solution please. Thank you!

Try this:

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();

With Jquery You can do this :

    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); 
             });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM