Given a string like aaabba, I want a function which turns the a's to b's and the b's to a's, returning bbbaab.
I tried this clumsy one:
var newa = [];
function swit(x) {
for (var i = 0; i < x.length; i++) {
if (x[i] === 'a') {
newa.push('b');
}
else if (x[i] === 'b') {
newa.push('a');
}
alert(newa);
}
}
swit("aaab");
After clicking through a lot of alerts, finally, the last alert shows the intended result. But I want it without commas and at the first place – not after many iterations:
I also tried the string.replace() Method – in combination with a for-loop:
function swit(x) {
for (var i = 0; i < x.length; i++) {
if (x[i] === 'a') {
x.replace('a', 'b');
}
else if (x[i] === 'b') {
x.replace('b', 'a');
}
alert(x);
}
}
swit("aaab");
But nothing changes. Why?
Could you please give me a hint of what went wrong and how to get the desired result?

myString.replace(/somePattern/g, 'replaceTo')or with use ofnew RegExp(options). Playground here: regexr.com, my quick (may not work the way you want it to but you get the idea) example here: jsfiddle.net/b1hgtnfy/11