Swap two letters in the same string with each other

Swap two letters in the same string with each other
0

#1

The objective is to allow strings such as

aaacbbb

to become

bbbcaaa

bbbbccaa

to become

aaaaccbb

I have done the following so far

function switcheroo(str){


let strArr = str.split('');

for (let i = 0 ; i<strArr.length; i++) {

if ( strArr[i] === 'a' ) {

strArr[i] = 'b';


}


}

return strArr.join('');

}

I now realise, an attempt to have another if statement that will swap all element ‘b’ with ‘a’ will just lead to a final returned string that either makes ALL as become bs or vice versa

How can this be done such that two specified letters in a string are simply swapped?


#2

So, instead use an else if statement and that would do your job.
Hope that answers your question.