replace a substring within a string in Javascript
Code snippet on how to replace a substring within a string in Javascript
let string = 'Hello World!';
let substring = 'World';
let replacement = 'Friend';
let newString = string.replace(substring, replacement);
console.log(newString);
This code replaces the substring ‘World’ with ‘Friend’ in the string ‘Hello World!‘. First, it creates three variable strings, ‘string’, ‘substring’, and ‘replacement’. ‘String’ is assigned the value ‘Hello World!‘. ‘Substring’ is assigned the value ‘World’ and ‘replacement’ is assigned the value ‘Friend’. Next, the ‘string.replace()’ method is used to replace the value of ‘substring’ with ‘replacement’ in the ‘string’ variable. The ‘string.replace()’ method is given two arguments, ‘substring’ and ‘replacement’, and the result is stored in the new variable ‘newString’. Finally, ‘console.log(newString)’ is used to output the new string which should now be ‘Hello Friend!‘.