On the last page you extracted part of a string of text. In the example used that means you now know a name (Fred). We will ignore the previous code because it was getting a bit long. Start a new page and call it replace.html.
Place this code inside the script element (no function this time just to be lazy):
var reallyLongString='This is a sentence which uses the word Fred once. This is a sentence which uses Fred (that is fred) twice - or does it?'; var newVersion=reallyLongString.replace('Fred', 'John'); alert(newVersion);
Try it. What it does is fairly clear but why only change the first one? How do you change the other two? The answer brings up a subject which you probably do not want to learn just yet. Regular expressions are ways of matching text very flexibly. How they work gets very complicated but for this you only need to know a couple of things:
- to tell it to match all occurrences you add the global modifier g
That line of code will now look like this:
var newVersion=reallyLongString.replace(/Fred/g, 'John');