ES2021에서 replaceAll() 메서드가 추가되었다. 하지만 코테를 준비할 때 채점 환경에 따라 ES2021이 도입되지 않은 곳이 있는데 해당 환경에서는 replaceAll()을 사용할 수 없다. 따라서 replaceAll()을 구현해보겠다.
let str = "hello, world";
str = str.replace("l", 7);
console.log(str);
//he7lo, world
let str = "hello, world";
str = str.replaceAll("l", 7);
console.log(str);
//he77o, wor7d
let str = "hello, world";
str = str.split("l");
console.log(str);
// ["he", "", "o wor", "d"]
split("l")을 사용하면 아래와 같은 배열이 만들어진다.
index | 0 | 1 | 2 | 3 |
---|---|---|---|---|
value | he | o wor | d |
let str = "hello, world";
str = str.split("l");
str = str.join(7);
console.log(str);
// he77o, wor7d
let str = "hello, world";
str = str.split("l").join(7);
console.log(str);
// he77o, wor7d