JavaScript Objects: Finishing Strings - The Replace() Method
(Page 2 of 6 )
Suppose you created a string containing the sentence "I love my girlfriend Moniqua." When you guys break up, you may want to change that name to the name of your new girlfriend. You could use the Replace() method to do just that:
<html>
<body>
<script type="text/javascript">
var girlfriend="I love Moniqua!"
document.write(girlfriend.replace(/Moniqua/,"Jolie"))
</script>
</body>
</html>
The result of the above code would be:
I love Jolie!
All we did was create a variable named girlfriend, and assign the value “I love Moniqua!” to it. Next, after having broken up with Moniqua for having a really dumb name, we used the Replace() method to swap out Moniqua for Jolie. Take that Brad Pitt!
You will note that the Replace() method is case-sensitive. If you want to do a replace and not have to worry about whether or not the string is upper or lower case, you can do this:
<html>
<body>
<script type="text/javascript">
var girlfriend="I love Moniqua!"
document.write(girlfriend.replace(/moniqua/i,"Jolie"))
</script>
</body>
</html>
It's the same exact code, only this time we added an “i” after moniqua and before the comma seperator.
It results in the same thing of course:
I love Jolie!
Say you have multiple words to replace. Maybe you wrote a whole poem for Moniqua, and being the romantic guy that you are, you've decided to delete her name and insert Jolie's name in its place. How thoughtful.
<html>
<body>
<script type="text/javascript">
var str="My Dear Moniqua! "
str=str + "I love thee Moniqua, "
str=str + "The way you love Pork Chops; "
str=str + "Like your cholosterol filled veins, "
str=str + "Everytime I see you my heart stops. "
str=str + "<br />Moniqua, Moniqua, Moniqua"
document.write(str.replace(/Moniqua/g, "Jolie"))
</script>
</body>
</html>
Pretty simple code right? You will notice here that we used the “g” after the name Moniqua to signify a Global Replace. This replaces all of the Moniquas in the program with Jolies. Here is the result:
My Dear Jolie! I love thee Jolie, The way you love Pork Chops; Like your cholosterol filled veins, Everytime I see you my heart stops.
Jolie, Jolie, Jolie
Again note that the function is case-sensitive. So if we had used a lower case moniqua, nothing would have changed.
To remedy this matter, we simply add an “i” as before:
<html>
<body>
<script type="text/javascript">
var str="My Dear Moniqua! "
str=str + "I love thee Moniqua, "
str=str + "The way you love Pork Chops; "
str=str + "Like your cholosterol filled veins, "
str=str + "Everytime I see you my heart stops. "
str=str + "<br />Moniqua, Moniqua, Moniqua"
document.write(str.replace(/Moniqua/gi, "Jolie"))
</script>
</body>
</html>
Next: The Search() Method >>
More JavaScript Articles
More By James Payne