Raul Rodriguez Raul Rodriguez - 1 year ago 50
Javascript Question

fix error in string where numbers are replacing letters

I am trying to fix a string that has errors. In a string

S
is misinterpreted as
5
,
O
is misinterpreted as
0
and
I
is misinterpreted as
1
.

See the following examples.

correct("L0ND0N") => "LONDON"


correct("BUDAPE5T"),"BUDAPEST"


I have been looking at my code for ages and have no idea why it isn't working. See code below.

Can anyone see what mistake I am making?

The challenge is taken from here.

function correct(string){
let fix = {
"5": "S",
"1": "I",
"0": "O"
}
let strArr = string.split("");

return strArr.map(item => {
for(var key in fix){
if(item === key){
return fix[key]
} else {
return item;
}
}
}).join('');

}

Answer Source

You can pass a callback to String.replace which will make this task easier:

function correct(str) {
    let fix = {
        "5": "S",
        "1": "I",
        "0": "O"
    };
    return str.replace(/(\d)/g, a => fix[a] || a);
}
console.log(correct("BUDAPE5T"));

For your original question, your for loop isn't looping, but you are returning on the first iteration of it. Change it to

return strArr.map(item => {
    let f;
    for(var key in fix){
        if(item === key){
            f = fix[key]
        } else {
            f = item;
        }
    }
    return f;
}).join('');

and it'll work too (but better go with the replace function).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download