Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: replace 'g' character

I would like to replace g characters on the following innerHTML div:

<div id="myDiv">aaa>aga</div>

I used

var myDiv = document.getElementById('myDiv');
myDiv.innerHTML = myDiv.innerHTML.replace('g','a');

Unfortunately, this replace also the > character by &at;.
How can I do to avoid this behavior ?

like image 844
puglic Avatar asked Apr 27 '26 20:04

puglic


2 Answers

Try use .innerText instead of .innerHTML, like so

var myDiv = document.getElementById('myDiv');
var text  = myDiv.innerText || myDiv.textContent || '';

myDiv.innerHTML = text.replace(/g/g, 'a');

// or without variable 
// myDiv.innerHTML = (myDiv.innerText || myDiv.textContent || '').replace(/g/g, 'a');
<div id="myDiv">aaa>aga</div>
like image 124
Oleksandr T. Avatar answered Apr 29 '26 09:04

Oleksandr T.


If you want to be extra safe (when dealing with elements that contain other elements, or text that you don't want interpreted as HTML), you'll want to loop through the element's children to find Text nodes within.

A simple replacement inside the Text nodes will get you what you want:

 function replaceIn(el, pattern, replacement) {
   if (el.nodeType == 3) {   // TEXT_NODE
     el.nodeValue = el.nodeValue.replace(pattern, replacement);
   } 
   else {
     var n = el.childNodes.length;
     
     for (var i = 0; i < n; ++i)
       replaceIn(el.childNodes[i], pattern, replacement);
   }
 }

 replaceIn(document.getElementById('foo'), /two/g, 'dos');
<div id="foo">
  <p>one</p>
  <p><em>two</em>
  </p>
  one two &lt;em&gt;three&lt;/em&gt; four two two three four
</div>
like image 31
Paul Roub Avatar answered Apr 29 '26 09:04

Paul Roub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!