Javascript DOM How to - Find certain words and replace them








Question

We would like to know how to find certain words and replace them.

Answer


<!DOCTYPE html>
<html>
<head>
</head><!--from  ww  w  .ja  v  a2  s .com-->
<body>
  <div id="dont-replace-them">
    New York<br /> 
  </div>
  <br />
  <div id="replace-them">
    New York<br /> 
  </div>
  <script type="text/javascript">
function replaceWords() {
    document.getElementById("replace-them").innerHTML = document.getElementById("replace-them").innerHTML.replace("New York", "New York City");
    
}  
replaceWords();
</script>
</body>
</html>

The code above is rendered as follows: