.replace() Method
Use the .replace()
method to search for a certain string and replace it with another. Take this sentence for example: "Your baby is going to be awesome regardless of it's gender." The sentence is incorrect; it uses the contraction it's (it is) rather than the possessive its. We can fix that using the .replace()
method.
var wrong = "Your baby is going to be awesome regardless of it's gender.";
//replace it's with its
var notWrong = wrong.replace("it's", "its");
console.log(notWrong);
Output
`Your baby is going to be awesome regardless of its gender.`
The one important thing to note is that the .replace()
method is set up like so:
.replace("old", "new");
The first argument is what you want to replace and the second argument is what you want to replace it with.
By adding g
for global and i
for case insensitive, you can replace any instance of a string, regardless of whether it is upper or lowercase.
var str = "I have experience with HTML, C#, and javascript. Javascript is the language I enjoy the most.";
//search for any instance of "javascript" and replace it with "JavaScript"
var strNew = str.replace(/javascript/gi, "JavaScript");
console.log(strNew);
Output
`I have experience with HTML, C#, and JavaScript. JavaScript is the language I enjoy the most.`
Last updated