초보 개발자의 일기

A를 #으로 본문

코딩테스트/JS 알고리즘 문제(JS)

A를 #으로

판다꼬마 2022. 8. 5. 16:26
728x90

문제

 

입력

  • 첫 번째 줄에 문자열이 입력된다.

 

출력

  • 첫 번째 줄에 바뀐 단어를 출력한다.

 

입력 예시

BANANA

출력 예시

B#N#N#

풀이 방법

정규식으로 찾으려는 문자열은 '/'로 감싸서, 파라미터로 들어가는 값이 정규식 임을 알려주고,

 '/' 뒤에는 'g'라는 modifier를 붙였다.

g는 'global match'라는 의미로 사용했다.

 

내 코드

<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>

Solution

<html>
    <head>
        <meta charset="UTF-8">
        <title>출력결과</title>
    </head>
    <body>
        <script>
            function solution(s){
                let answer="";
                for(let x of s){
                    if(x=='A') answer+='#';
                    else answer+=x;
                }
                return answer;
            }
            
            let str="BANANA";
            console.log(solution(str));
        </script>
    </body>
</html>



<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>

느낀 점

 

728x90

'코딩테스트 > JS 알고리즘 문제(JS)' 카테고리의 다른 글

가장 긴 문자열  (0) 2022.08.12
대소문자 변환  (0) 2022.08.11
일곱 난쟁이  (0) 2022.08.05
10부제  (2) 2022.08.04
홀수  (0) 2022.08.03