Algorithm
-
Input:
- Take the original string as input.
- Take the character to be replaced as input.
- Take the new character to replace with as input.
-
Initialize:
- Initialize an empty string to store the result.
-
Loop through the original string:
- Use a loop to iterate through each character in the original string.
-
Check and Replace:
- For each character, check if it is equal to the character to be replaced.
- If yes, replace it with the new character; otherwise, keep it unchanged.
-
Build the Result String:
- Concatenate each character (either replaced or unchanged) to the result string.
-
Output:
- Display or return the resulting string.
Code Examples
#1 Code Example- Replace First Occurrence of a Character in a String
Code -
Javascript Programming
// program to replace a character of a string
const string = 'Mr Red has a red house and a red car';
// replace the characters
const newText = string.replace('red', 'blue');
// display the result
console.log(newText);
Copy The Code &
Try With Live Editor
Output
Mr Red has a blue house and a red car
#2 Code Example- Replace Character of a String Using RegEx
Code -
Javascript Programming
// program to replace a character of a string
const string = 'Mr Red has a red house and a red car';
// regex expression
const regex = /red/g;
// replace the characters
const newText = string.replace(regex, 'blue');
// display the result
console.log(newText);
Copy The Code &
Try With Live Editor
Output
Mr Red has a blue house and a blue car
Demonstration
JavaScript Programing Example to Replace Characters of a String-DevsEnv