-
[프로그래머스] 숫자 문자열과 영단어 - javascript기타/코딩테스트 2022. 6. 14. 13:30
문제
네오와 프로도가 숫자놀이를 하고 있습니다. 네오가 프로도에게 숫자를 건넬 때 일부 자릿수를 영단어로 바꾼 카드를 건네주면 프로도는 원래 숫자를 찾는 게임입니다.
다음은 숫자의 일부 자릿수를 영단어로 바꾸는 예시입니다.- 1478 → "one4seveneight"
- 234567 → "23four5six7"
- 10203 → "1zerotwozero3"
이렇게 숫자의 일부 자릿수가 영단어로 바뀌어졌거나, 혹은 바뀌지 않고 그대로인 문자열 s가 매개변수로 주어집니다. s가 의미하는 원래 숫자를 return 하도록 solution 함수를 완성해주세요.
참고로 각 숫자에 대응되는 영단어는 다음 표와 같습니다.
내 풀이
function solution(_s) { const number = [ /zero/gi, /one/gi, /two/gi, /three/gi, /four/gi, /five/gi, /six/gi, /seven/gi, /eight/gi, /nine/gi, ]; number.forEach((value, index) => (_s = _s.replace(value, index))); return parseInt(_s); }
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
String.prototype.replaceAll() - JavaScript | MDN
The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match.
developer.mozilla.org
replaceAll 함수는 런타임 에러가 난다. 왜 ... 그럴까?
실행 테스트
const s = "one4seveneight"; console.log(solution(s)); // output => 1478
'기타 > 코딩테스트' 카테고리의 다른 글
[프로그래머스] 로또의 최고 순위와 최저 순위 - javascript (0) 2022.06.21 [프로그래머스] 키패드 누르기 - javascript (0) 2022.06.16 [프로그래머스] 실패율 - javascript (0) 2022.06.13 [프로그래머스] 폰켓몬 - javascript (0) 2022.06.13 [프로그래머스] 신규 아이디 추천 - javascript (0) 2022.06.13