A를 #으로

minho·2021년 9월 7일
0

code

function solution(s){
                let answer= str;
                let replaced_answer = answer.replace(/A/g, '#')
                //js replace() 활용
                // replace('str', 'newStr') -> 찾은 맨 앞의 글자만 변경
                // replace(/str/g, 'newStr') -> str에 해당되는 모든 문자 변경
                return replaced_answer;
            }            
            let str="BANANA";
            console.log(solution(str));

알게된 점

replace

replace(regexp|substr, newSubstr|function)

  • regexp (pattern)
    정규식(RegExp) 객체 또는 리터럴. 일치하는 항목은 newSubStr 또는 지정된 함수(function)가 반환 한 값으로 대체됩니다.

  • substr (pattern)
    newSubStr로 대체 될 String. 정규식이 아닌 글자 그대로의 문자열로 처리됩니다. 오직 첫 번째 일치되는 문자열만이 교체됩니다.

  • newSubStr (replacement)
    첫번째 파라미터를 대신할 문자열(String). 여러가지 대체 패턴들이 지원됩니다.

  • function (replacement)
    주어진 regexp 또는 substr에 일치하는 요소를 대체하는 데 사용될 새 하위 문자열을 생성하기 위해 호출되는 함수.

replace('str', 'newStr') -> 찾은 맨 앞글자만 변경
replace(/str/g, 'newStr') -> 전체 글자 변경
이때 /str/ 은 ''를 붙이지 않는다.

  • g는 global이란 뜻으로 전체를 의미한다.
  • g다음 i를 붙이면 ignore이란 뜻으로 대소문자 구분이 없음을 의미한다.

EX)

const str = 'MMGGLLEM';
str.replace(/M/g, 'S')
# str = 'SSGGLLES'
profile
Live the way you think

0개의 댓글