OneBite.Dev - Coding blog in a bite size

replace a word in a string in Javascript

Code snippet on how to replace a word in a string in Javascript

let str = "Hello, my name is Dan";
let newStr = str.replace("Dan", "Sandra");
console.log(newStr); // Hello, my name is Sandra

This code snippet uses the replace() method in Javascript to replace a word in a string. The replace() method looks for the first argument (“Dan” in this example) and replaces it with the second argument (“Sandra” in this example). We start off by declaring a variable named “str” with the string “Hello, my name is Dan”. Then we create a new variable named “newStr” that uses the string variable and the replace() method to look for the first argument, “Dan”, and replaces it with the second argument, “Sandra”. Finally, we use the console.log() method to output the result of the “newStr” variable which is “Hello, my name is Sandra”.

javascript