Javascript:替换'g'字符

Javascript: replace 'g' character

我想替换以下 innerHTML div 中的 g 个字符:

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

我用过

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

不幸的是,这也将 > 字符替换为 &at;
我该如何避免这种行为?

尝试使用 .innerText 而不是 .innerHTML,像这样

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>

如果你想更加安全(在处理包含其他元素的元素,或者你不想解释为 HTML 的文本时),你需要遍历元素的子元素以在其中找到文本节点。

在文本节点内进行简单的替换即可满足您的需求:

 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>