PUBLISHED ON: FEBRUARY 16, 2023
JavaScript program to Replace Characters of a String
This JavaScript program to replace characters of a string allows programmers to replace certain characters within a given string with different ones. This can be incredibly useful for a variety of applications, from correcting typos to formatting data.
In this article, we will dive into the details of how to write a JavaScript program that replaces characters of a string. We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.
Method 1 : Replace First Occurrence of a Character in a String
The replace()
method is used to replace the specified string with another string , but the drawback is that it will only replace the first occurrence.
// JavaScript program to replace a character of a string
const sentence = 'Mr John has a red house and a red car';
// replace the characters
const newSentence = sentence.replace('red', 'blue');
console.log(newSentence);
Mr John has a blue house and a red car
Method 2 :Replace Character of a String Using RegEx
A regex expression is used as the first parameter inside the replace()
method. Since, JavaScript is case-sensitive, R and r are treated with different values.
// JavaScript program to replace a character of a string
const sentence = 'Mr John has a red house and a red car';
// regex expression (regex)
const regex = /red/g;
// replacing the characters
const newText = sentence.replace(regex, 'blue');
console.log(newText);
Mr John has a blue house and a blue car
Conclusion
In conclusion, replacing characters in a string can be a tedious and time-consuming task, but with the help of interactive JavaScript programs, it can be made quick and easy. By using the program outlined in this blog, you can easily replace characters in your strings with just a few clicks. This not only saves time but also helps to improve the overall efficiency of your workflow.
We hope that this blog has been informative and helpful in explaining how to replace characters in a string using JavaScript.