알고리즘, 자료구조/프로그래머스

프로그래머스/핸드폰 번호 가리기/javascript

soohkang 2021. 7. 8. 17:09
728x90

처음 코드

String.prototype.replaceAt=function(index, char) {
    var a = this.split("");
    for(let i = 0; i < index - 4; i++) {
        a[i] = char;
    }
    return a.join("");
}
function solution(phone_number) {
    var answer = '';
    
    let numLen = phone_number.length;
    
    answer = phone_number.replaceAt(numLen, '*');
    
    return answer;
}

 

  • 제시된 phone_number를 인덱스 0부터 뒷 4자리 제외한 인덱스를 찾아서 *를 교체하려고 했다.
  • 구글링 해보니 replace만으로 인덱스 범위를 지정할 수 없어서 아래 오버플로우 사이트에서 힌트를 얻어서 코드를 작성했다.

https://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript

 

How do I replace a character at a particular index in JavaScript?

I have a string, let's say Hello world and I need to replace the char at index 3. How can I replace a char by specifying a index? var str = "hello world"; I need something like str.replaceAt(0,"...

stackoverflow.com

String.prototype.replaceAt을 작성했는데 0인 덱스부터 뒷자리 4자리 제외한 범위만큼 * 로 교체해서 리턴하는 함수다.