replace 함수

SUN·2023년 3월 15일

JS 함수

목록 보기
3/8

설명

문자열을 바꿀 수 있다.

구문

var newStr = str.replace(regexp|substr, newSubstr|function)
  • regexp : 정규식 - 정규식 객체나 리터럴 값, 정규식에 일치하는 새부분 문자열을 새로운 문자열이나 함수로 치환가능

  • substr : 부분 문자열 - 새로운 문자로 바꿀 타켓 문자열이다.

  • newSubstr : 새 부분 문자열 - 지정된 부분문자열을 대체할 문자이다.

  • function : 함수 - 주어진 정규식 또는 부분문자열에 일치하는 요소를 대체할 때 사용

예시

1. 기본 작동

let text = 'aabbcc';
let reText = text.replace("b","a")

console.log(text) //aabbcc
console.log(reText) //aaabcc

가장 첫 문자열을 바꿔준다.

모든 문자를 바꿀려면 정규식을 사용해야한다.

1-1 정규식을 사용

let text = 'aabbcc';
let reText = text.replace(/b/gi ,"a")

console.log(text) //aabbcc
console.log(reText) //aaaacc

g (global) : 전체 매치
i (insensitive) : 대소문자 구분제거

즉 대소문자 구분없이 모든 b문자를 a로 바꾸라는 의미이다.

1-2 함수를 사용

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

https://deeplify.dev/front-end/js/replace-and-replace-all

profile
안녕하세요!

0개의 댓글