Swap Characters JS function

Hello, dear experts. I have a task to code a JS function that takes three arguments, a string, character 1 and character 2. The function replaces all instances of c1 with c2, and vice versa. The function returns the updated string. All the code should be executed WITHOUT using any built-in methods like “split()” or “toString()” or “IndexOf().
Example:
function( “aabbccc”, “a”, “b”)➔"bbaaccc”
function(“random w#rds writt&n h&r&”, “#”, “&”)➔"random w&rds writt#n h#r#"
function(“128 895 556 788 999”, “8”, “9”)➔"129 985 556 799 888"

So any suggestions are appreciated.

Hint - you can loop over strings like you can loop over arrays.

Thank you, I’ll try that!

You’re absolutely right, RandellDawson, I’m not expecting the others to do the coding for me, but this assignment is truly harsh on me, I do not know where to start…

So, I’ve done the research and have for now this block of code:

function changeChars (string, c1,c2){

let result = string.split(' ');

let len = res.length;

let  disp = ' ';
for( i = 0;  i < len;  i++)
{
       if(result[i]  ==  c1)
       {
           disp +=  c2;
       }
       else if(result[i] == c2);
       {
       disp += c1;
       }
       else {
           disp +=  result[i];
       }    
            return disp;

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.