I hate to proof read my work. Now Imagine finding that you have built a site with very pertinent information, let’s say a biography , and you just so happen to spell the subjects name wrong, let’s call him Bob, but it’s actually spelled Bobb. Now your issue is that this bio is thousands of words long and the time it’s going to take you to go through and fix this word for word is going to be too much. Well, you are in luck; this is where the Replace Method comes into play using Javascript.

First we will need to find this particular variable, Bob, in our biography. Before we can do so, we will need to take the biography and convert it to a string so we can work with it. We will use the document.body.innerHTML function and set it to a variable that will contain our bio like so:

We used over 10 web hosting companies before we found Server Intellect. They offer dedicated servers, and they now offer cloud hosting!

Code Block
HTMLPage.htm
Establish document body as a string variable.
 var s = document.body.innerHTML;
Then we will need to establish the variable in which we need to replace, Bob in our case.
Now with that taken care of we can begin our search. In order to search for our variable “w” and not quit after the first find, we will need to use a Regular Expression, RegEx, to continue the search. Let’s establish a new variable that contains this expression.

We stand behind Server Intellect and their support team. They offer dedicated servers, and they are now offering cloud hosting

Code Block
HTMLPage.htm
Creating a new variable that contains our Regular Expression.
var w = "Bob";
var
 RegEx = new RegEx(w, 'g');
Regex ‘g’ stand for “Continue at the end of the previous match.”
 
Next what we will need to do is replace the faulty Bob with our new and improved Bobb and set it back to the Body of our site. The replace function is built so you first establish what you are looking for and then the replacement, separated by a comma. This will look like so:

Code Block
HTMLPage.htm
Replace our string with our new variable that contains the replacement for “w.”
s = document.body.innerHTML.replace(RegEx, ("Bobb"));
And there you have it! You have now created your very own search engine in JavaScript. This can also be simplified into a single line of code. This is all contained in the Source Code download at the bottom as well as a few more examples. Thanks for joining me; I hope you have found this helpful. Until next time and take care.

We chose Server Intellect for its cloud hosting, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.

ReplaceJavaScriptTut.zip