replace

» JavaScript

replace

문자열에서 ‘특정 문자열’을 찾아서 ‘치환’해주는 함수

string.replace(search, new);

문자열에서 search 값을 찾아 new 값으로 치환함

예제

let spell = "a, b, c";
let chg = spell.replace("b", "c");
console.log(chg); // 'a, c, c'

but 첫번째로 찾은 문자열만 치환해주는 단점이 있음 그래서 모든 문자열 치환하는 방법이 있다

let spell = "a, b, c, b";
let chg = spell.replace("/b/g", "c");
console.log(chg); // 'a, c, c, c'

/로 감싸준 문자열은 정규식임을 알려주는 것이며 뒤에 g는 global match라는 의미로 사용한 것