Algorithm


  1. Input:

    • Accept the original string (originalString).
    • Accept the character to be replaced (oldChar).
    • Accept the new character that will replace the old one (newChar).
  2. Validation:

    • Ensure that originalString is not empty.
    • Ensure that oldChar is a single character.
    • Ensure that newChar is a single character.
  3. Initialization:

    • Initialize an empty string (resultString) to store the modified string.
  4. Loop through the characters:

    • Use a loop to iterate through each character of originalString.
  5. Replace oldChar:

    • Check if the current character is equal to oldChar.
    • If true, append newChar to resultString.
    • If false, append the current character to resultString.
  6. Output:

    • Print or return the resultString as the final modified string.

 

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

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

x
+
cmd
LeArning JAvAScript ProgrAm
Advertisements

Demonstration


JavaScript Program to Replace all Instances of a Character in a String-DevsEnv

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