You can use the replace() method to replace all occurrences of a character or substring in a string in JavaScript. The method takes two arguments: the first is the substring you want to replace, and the second is the replacement substring. Here’s an example:

let str = "Hello, world!";
let newStr = str.replace(/o/g, "0");
console.log(newStr); // "Hell0, w0rld!"

The above example replaces all occurrences of the letter “o” with the number “0”. Note that the first argument is a regular expression with the global flag /g set so that it matches all occurrences of the letter “o” in the string.

You can also use the replace() method with a string for the first argument, but it will only replace the first occurrence of the string.

let str = "Hello, world!";
let newStr = str.replace("world", "javascript");
console.log(newStr); // "Hello, javascript!"

You can also use split() and join() method to replace all the characters in a string with new one.

let str = "Hello, world!";
let newStr = str.split("").join("*");
console.log(newStr); // "*********, *******!"

This splits the string into an array of characters, then joins them back together with the replacement character “*”.

Also Read:

Categorized in: