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:
- What Is AJAX?
- List of JavaScript Functions
- How To Copy An Array In JavaScript
- How To Get All Unique Values In A JavaScript Array
- Convert int to string in JavaScript
- How To Check If An Object Is An Array In JavaScript
- How To Randomize An Array In JavaScript
- How To Replace All Occurrences Of A Character In A String?
- How To Split A String In JavaScript?
- How To Replace Multiple Spaces With Single Space In JavaScript
- How To Replace All Character In A String In JavaScript
- How To Check If A String Contains A Substring In JavaScript
- How To Loop Through An Array In JavaScript
- How To Check If A Value Exists In An Array In JavaScript
- How To Remove Duplicates From An Array Using JavaScript
- How To Create Multiline Strings In JavaScript
- How To Remove A Specific Element From An Array In JavaScript
- How To Define A Function In JavaScript?
- How To Concatenate Two String Arrays In JavaScript
- How To Get Image Size (Height & Width) Using JavaScript
- How To Change Image Size In JavaScript
- How To Increase and Decrease Image Size Using JavaScript
- How To Trigger Or Pause A CSS Animation In JavaScript
- How To Check If A Variable Is Undefined Or Null In JavaScript
- How To Check If A Variable Exists Or Is Defined In JavaScript
- How To Change The Background Color With JavaScript
- How To Encode A URL With JavaScript
- How To Decode A URL In JavaScript