In JavaScript, you can use the built-in .replace() method to replace all occurrences of a character in a string. The method takes two arguments: the first is the character or substring you want to replace, and the second is the character or substring you want to replace it with.

For example, if you want to replace all occurrences of the letter “a” with the letter “b” in the string “javascript”, you would use the following code:

<pre class="wp-block-syntaxhighlighter-code">
let str = "javascript";
let newStr = str.replace(/a/g, "b");
console.log(newStr);
</pre>

This would output “jbvbscript”.

You can also use the .split(), .join() method.

let str = "javascript";
let newStr = str.split("a").join("b");
console.log(newStr);

You can also use replaceAll() method if you are using ECMAScript 2021 or later.

let str = "javascript";
let newStr = str.replaceAll("a", "b");
console.log(newStr);

Note: The .replace() method only replaces the first occurrence of the character unless we use the ‘/g’ flag to replace all occurrences of the character globally.

Also Read:

Categorized in: