[Problem Solving] 특정 문자 제거

Sean·2022년 12월 26일
0

Problem Solving

목록 보기
5/130

문제

문자열 my_string과 문자 letter이 매개변수로 주어집니다. my_string에서 letter를 제거한 문자열을 return하도록 solution 함수를 완성해주세요.

제한사항

  • 1 ≤ my_string의 길이 ≤ 100
  • letter은 길이가 1인 영문자입니다.
  • my_stringletter은 알파벳 대소문자로 이루어져 있습니다.
  • 대문자와 소문자를 구분합니다.

입출력 예시

my_stringletterresult
"abcdef""f""abcde"
"BCBdbe""B""Cdbe"

통과한 풀이

function solution(my_string, letter) {
    var answer = '';
    
    while(my_string.includes(letter)){
        my_string = my_string.replace(letter, '');
    }
    
    answer = my_string;
    return answer;
}

아이디어

  • String.prototype.replace()를 사용한다.
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll
  • 문자열을 굳이 for문 같은 반복문을 통해서 돌면서 제거 할 필요 없다.
  • replace 함수를 쓰면 알아서 대체해준다.
  • 대신, replace 함수는 모든 letter에 대해서 대체해주는 것이 아니므로, while에서 includes 조건을 확인해야한다.
  • Tip) while문도 돌 필요 없이 replaceAll을 사용하면 한 줄에 끝내버릴 수 있다.
profile
여러 프로젝트보다 하나라도 제대로, 깔끔하게.

0개의 댓글