5_hyun 2022. 8. 5. 21:35
반응형

해결법

이 문제에서는 for문도 사용 가능하다. 하지만 정규표현식으로 푼다면 더 효율적으로 풀 수 있다.

replace(/A/, '#') 이렇게 한다면 전체 중에서 하나의 A만 바꿔준다. 따라서 replace(/A/g, '#') 이렇게 해야 전역적으로 A를 다 찾아서 바꿔준다.

 

코드

<html>
  <head>
    <meta charset="UTF-8" />
    <title>출력결과</title>
  </head>
  <body>
    <script>
      function solution(s) {
        let answer = s;

        answer = answer.replace(/A/g, "#");

        return answer;
      }

      let str = "BANANA";
      console.log(solution(str));
    </script>
  </body>
</html>
반응형