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.

Please either post the code you have written so far or show us your documented algorithm of the steps necessary to complete the task. Once we know you understand the steps needed, we can help guide you to a solution.

Are you sure this is the correct return value? I expect the above call to return "bbbbccc" based on the description.

Edit: Nevermind. I understand the requirements now better.

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

Thank you, I’ll try that!

So you need to write out the steps you believe are necessary to accomplish the task, then we can guide you to the code necessary. We are not just going to write the code for you. You must put some effort into figuring out the logic.

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 (’).

I thought you stated that you could not use built-in functions. Anyway, why did you choose to split on a single space character?

Also, can you explain your reasoning of why you are initializing disp as a space character?

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