Algorithm


  1. Input:

    • Take the original string as input.
    • Take the character to be replaced as input.
    • Take the new character to replace with as input.
  2. Initialize:

    • Initialize an empty string to store the result.
  3. Loop through the original string:

    • Use a loop to iterate through each character in the original string.
  4. 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.
  5. Build the Result String:

    • Concatenate each character (either replaced or unchanged) to the result string.
  6. 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

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

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

Demonstration


JavaScript Programing Example to Replace Characters of a String-DevsEnv

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