javascript

replaceAll method 만들기

FaustK 2020. 1. 16. 22:09

javascript split method 와 join method 를 이용해서 replaceAll method 를 구현해 볼 수 있다.

 

String.prototype.replaceAll = function(searchVal, replaceVal) {
  return this.split(searchVal).join(replaceVal);
};

const str = 'hello';
let changeStr = str.replaceAll('l', '1'); // 'he11o'

changeStr; // 'he11o;
str; // 'hello'  

How working split method and join method

join 메서드를 사용하면 ' , '  사이에 인자가 들어간다 ^^