correctError.js (8kyu 42)
Codewars 알고리즘 풀이
Problem
- Your task is correct the errors in the digitised text.
- 디지털화된 텍스트의 에러를 수정한다.
Errors
O
is misinterpreted as0
I
is misinterpreted as1
S
is misinterpreted as5
Solution 01
function correctError(str) {
let result = '';
for (let i = 0; i < str.length; i++) {
if (str[i] === '0') {
result += 'O';
} else if (str[i] === '1') {
result += 'I';
} else if (str[i] === '5') {
result += 'S';
} else {
result += str[i];
}
}
return result;
}
correctError('PAR15'); // PARIS
correctError('L0ND0N'); // LONDON
correctError('C0DEWAR5'); // CODEWARS
Solution 02
function correctError(str) {
let result = [];
for (let i = 0; i < str.length; i++) {
if (str[i] === '0') {
result.push('O');
} else if (str[i] === '1') {
result.push('I');
} else if (str[i] === '5') {
result.push('S');
} else {
result.push(str[i]);
}
}
return result.join('');
}
correctError('PAR15'); // PARIS
correctError('L0ND0N'); // LONDON
correctError('C0DEWAR5'); // CODEWARS
Solution 03
function correctError(str) {
return str.replace(/0/g, 'O').replace(/1/g, 'I').replace(/5/g, 'S');
}
correctError('PAR15'); // PARIS
correctError('L0ND0N'); // LONDON
correctError('C0DEWAR5'); // CODEWARS
정규표현식 (RegExp)
replace()
: 대응되는 문자열을 찾아 다른 문자열로 치환한다.
g
: 전역 검색