Algorithm
-
Input:
- Accept the original string (
originalString
). - Accept the character to be replaced (
oldChar
). - Accept the new character that will replace the old one (
newChar
).
- Accept the original string (
-
Validation:
- Ensure that
originalString
is not empty. - Ensure that
oldChar
is a single character. - Ensure that
newChar
is a single character.
- Ensure that
-
Initialization:
- Initialize an empty string (
resultString
) to store the modified string.
- Initialize an empty string (
-
Loop through the characters:
- Use a loop to iterate through each character of
originalString
.
- Use a loop to iterate through each character of
-
Replace oldChar:
- Check if the current character is equal to
oldChar
. - If true, append
newChar
toresultString
. - If false, append the current character to
resultString
.
- Check if the current character is equal to
-
Output:
- Print or return the
resultString
as the final modified string.
- Print or return the
Code Examples
#1 Code Example-Replace All Instances Of a Character Using Regex
Code -
Javascript Programming
// program to replace all instances of a character in a string
const string = 'Learning JavaScript Program';
const result = string.replace(/a/g, "A");
console.log(result);
Copy The Code &
Try With Live Editor
Output
LeArning JAvAScript ProgrAm
#2 Code Example- Replace All Instances Of Character Using Built-in Methods
Code -
Javascript Programming
// program to replace all instances of character in a string
const string = 'Learning JavaScript Program';
const splitString = string.split('a');
const result = splitString.join('A');
console.log(result);
Copy The Code &
Try With Live Editor
Output
LeArning JAvAScript ProgrAm
Demonstration
JavaScript Program to Replace all Instances of a Character in a String-DevsEnv