Algorithm


  1. Input:

    • Take the input string.
    • Take the substring to be replaced.
    • Take the new substring that will replace the old one.
  2. Initialize Variables:

    • Initialize a variable to store the result string.
  3. Loop through the Input String:

    • Start a loop to iterate through each character in the input string.
  4. 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.
  5. Otherwise:

    • If the current position doesn't match the starting position of the substring, simply append the current character to the result string.
  6. Repeat:

    • Repeat the loop until you reach the end of the input string.
  7. 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

x
+
cmd
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

x
+
cmd
Mr blue has a blue house and a blue car
Advertisements

Demonstration


JavaScript Program to Replace All Occurrences of a String-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way