문자열을 바꿀 수 있다.
var newStr = str.replace(regexp|substr, newSubstr|function)
regexp : 정규식 - 정규식 객체나 리터럴 값, 정규식에 일치하는 새부분 문자열을 새로운 문자열이나 함수로 치환가능
substr : 부분 문자열 - 새로운 문자로 바꿀 타켓 문자열이다.
newSubstr : 새 부분 문자열 - 지정된 부분문자열을 대체할 문자이다.
function : 함수 - 주어진 정규식 또는 부분문자열에 일치하는 요소를 대체할 때 사용
let text = 'aabbcc';
let reText = text.replace("b","a")
console.log(text) //aabbcc
console.log(reText) //aaabcc
가장 첫 문자열을 바꿔준다.
모든 문자를 바꿀려면 정규식을 사용해야한다.
let text = 'aabbcc';
let reText = text.replace(/b/gi ,"a")
console.log(text) //aabbcc
console.log(reText) //aaaacc
g (global) : 전체 매치
i (insensitive) : 대소문자 구분제거
즉 대소문자 구분없이 모든 b문자를 a로 바꾸라는 의미이다.
let text = 'aabbcc';
function reTextfunc (txt) {
return 'a'
}
let reText = text.replace(/b/gi , reTextfunc)
console.log(text) //aabbcc
console.log(reText) //aaaacc
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/String/replace