Algorithm
-
Input:
- Take the input string.
- Take the substring to be replaced.
- Take the new substring that will replace the old one.
-
Initialize Variables:
- Initialize a variable to store the result string.
-
Loop through the Input String:
- Start a loop to iterate through each character in the input string.
-
Check for Substring:
- Check if the current position in the input string matches the starting position of the substring to be replaced.
- If it matches, append the new substring to the result string and move the pointer past the length of the substring.
-
Otherwise:
- If the current position doesn't match the starting position of the substring, simply append the current character to the result string.
-
Repeat:
- Repeat the loop until you reach the end of the input string.
-
Output:
- The result string now contains all occurrences of the original substring replaced with the new substring.
Code Examples
#1 Code Example- Replace All Occurrence of String Using RegEx
Code -
Javascript Programming
// program to replace all occurrence of a string
const string = 'Mr Red has a red house and a red car';
// regex expression
const regex = /red/gi;
// replace the characters
const newText = string.replace(regex, 'blue');
// display the result
console.log(newText);
Copy The Code &
Try With Live Editor
Output
Mr blue has a blue house and a blue car
#2 Code Example- Replace All Occurrence of String Using built-in Method
Code -
Javascript Programming
// program to replace all occurrence of a string
const string = 'Mr red has a red house and a red car';
const result = string.split('red').join('blue');
console.log(result);
Copy The Code &
Try With Live Editor
Output
Mr blue has a blue house and a blue car
Demonstration
JavaScript Program to Replace All Occurrences of a String-DevsEnv