Replace all occurrence in whole page " with (") double quotes

Hi,

I want to replace " in whole page using jquery or JavaScript with double quotes (")

I tried below but no solution.


<script>

var replaced = $("body").html().replace(/&quot;/g,'"');
$("body").html(replaced);

</script>

Any Idea?

-Thanks

Hi there edge,

try it like this, perhaps…

<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>untitled document</title>

<script>
(function( w, d ) {
   'use strict';
   w.addEventListener('load', 
      function() {
             d.body.textContent=
             d.body.textContent.replace(/ \&quot; /g, ' " ' );
            }, false );
}( window, document ) );
</script>

</head>
<body> 

 <div>
  &quot;one&quot; &quot;two&quot; &quot;three&quot;
 </div>

</body>
</html>

coothead

The jQuery .html() method basically gives you .innerHTML, which already unescapes HTML entities… so /&quot;/ won’t match anything. You need to access the .textContent here; compare

document.body.innerHTML = '&quot;'   // will render "
document.body.textContent = '&quot;' // will render &quot;

Also note that replacing the entire DOM like that is not a good idea anyway as it will void all element references and event listeners etc… I think the best you could do would be to recursively walk the DOM tree and only replace the .textContent of text nodes:

function walkReplace (node, pattern, replacment) {
  if (node.nodeType === 3) {
    // If the current node is a text node, do the replacement
    node.textContent = node.textContent.replace(pattern, replacment)
  } else {
    // Otherwise walk its children
    Array.from(node.childNodes).forEach(function (child) {
      walkReplace(child, pattern, replacment)
    })
  }
}

walkReplace(document.body, /&quot;/g, '"')

The question is why you’d want to do this in the first place though. :-P

(ninja’d)

Many thanks for support.

I got the solution. :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.