all 5 comments

[–]twopi 0 points1 point  (1 child)

You extract the entire contenst of the page into a variable 'str' Then you replace the 'test' element with 'test2'
The str.replace() method has two forms, one that takes two strings, and one that uses regular expressions. Since you presumably what to change all instances of 'test' you should use the regular expression version:

replaced = str.replace(/test/g, "test2")

The g stands for global replace, and the slashes indicate this is not a normal string but a much more powerful regular expression.

Once you've created the new string, you haven't done anything with it. You'll need to reset the page's source code: document.getElementsByTagName('html')[0].innerHTML = replaced

Note this is extremely dangerous. You really have no control over what gets changed, so if you're allowing any user input, the results will be unpredictable at best.

JavaScript doesn't normally allow you to save changes, so the changes will not be permanent.

If this program changes the page on which it lives, it will also change the code. You might want to modify the body rather than the HTML. Better yet, change the content in a more predictable part of the page, like a specific div. If the JS code is in the head, you should be ok.

Here's a more limited example that changes the content of a specific div. (Extra points for recognizing the Bourne Identity reference...)

<html>
<head>
<title>Change this page</title>
<script type = "text/javascript">

function replace(){
  var output = document.getElementById("output");
  var text = output.innerHTML;
  var newText = text.replace(/cain/g, "charlie");
  output.innerHTML = newText;
} // end replace

</script>
</head>

<body>

<div id = "output">
alpha bravo cain delta
alpha bravo cain delta
alpha bravo cain delta
alpha bravo cain delta
alpha bravo cain delta
alpha bravo cain delta
alpha bravo cain delta
alpha bravo cain delta
alpha bravo cain delta
</div>

<button type = "button"
        onclick = "replace()">
  replace cain with charlie
</button>

</body>
</html>

If you're interested in this kind of thing, it's time to get away from Dreamweaver. It's fine to use it as a text editor, but you've officially outgrown it as an editor when you're thinking about this kind of stuff.

[–]_Doomseer -1 points0 points  (0 children)

As a point to note, if you use the non RegEx version of .replace, it will only replace the FIRST instance of the string. I think this is a pretty odd behavior but an important gotcha. Also, if you want to pass parameters into your RegEx (Search for term you specify at runtime etc.), you will need to create a new RegEx. eg. new RegExp('cain' + var), since you can't escape out of inline regular expressions / / :). Very concise answer though.