JavaScript String Replace All

JavaScript String Replace AllIf you’ve spent any time coding in PHP you’ve probably had to use str_replace. This great function takes the value being searched for (the needle) and the value to replace it with runs through the subject (variable aka “haystack”) and effectively does a full find-and-replace with two simple parameters. In JavaScript we don’t have this same function, but we can actually achieve the same result with the replace() method.

This JavaScript will replace only the first occurance

str = str.replace("stringToFind","stringToReplaceWith")

This JavaScript will replace ALL values

str = str.replace(/stringToFind/g,"stringToReplaceWith")

What’s with the G?

G is for what I’m assuming is Global and provides the ability to search the entire source with this JavaScript method. Know what I mean?

10 thoughts on “JavaScript String Replace All

  1. I want to replace p1 by p2 how can i do that?? var p1=document.getElementById("word1").value); var p2=document.getElementById("word2").value; var cadena=document.getElementById("text1").value; document.write(str.replace(p1,p2));

  2. I want to replace p1 by p2 how can i do that?? var p1=document.getElementById("word1").value); var p2=document.getElementById("word2").value; var cadena=document.getElementById("text1").value; document.write(str.replace(p1,p2));

Leave a Reply

Your email address will not be published. Required fields are marked *