반응형
문자열 메서드 : replace() / replaceAll()
replace() 메서드는 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환합니다.
"문자열".relplace(찾을 문자열, 변경할 문자열)
"문자열".relplace(정규식)
"문자열".relplace(정규식, 변경할 문자열)
"문자열".relplace(정규식)
"문자열".relplace(정규식, 변경할 문자열)
const str1 = "javascript reference";
const currentStr1 = str1.replace("javascript", "자바스크립트"); // 자바스크립트 reference
const currentStr2 = str1.replace("j", "J"); // Javascript reference
const currentStr3 = str1.replace("e", "E"); // javascript rEference
const currentStr4 = str1.replaceAll("e", "E"); // javascript rEfErEncE
const currentStr5 = str1.replace(/e/g, "E"); // javascript rEfErEncE(g : global)
const currentStr6 = str1.replace(/e/gi, "E"); // javascript rEfErEncE(i : 대/소문자)
const str2 = "https://www.naver.com/img01.jpg";
const currentStr7 = str2.replace("img01.jpg", "img02.jpg"); //img01 -> img02
const str3 = "010-2000-1000";
const currentStr8 = str3.replace("-", ""); //0102000-1000
const currentStr9 = str3.replaceAll("-", ""); //01020001000
const currentStr10 = str3.replace(/-/g, ""); //01020001000
const currentStr11 = str3.replace(/-/g, " "); //010 2000 1000
const currentStr12 = str3.replace(/-/g, "★"); //010★2000★1000
const currentStr13 = str3.replace(/[1-9]/g, "★"); //0★0-★000-★000
replace()의 정규표현식 정의
다음 예제에서, 대소문자를 구분하지 않는 정규표현식을 replace()에 정의했습니다.
var str = 'Twas the night before Xmas...';
var newstr = str.replace(/xmas/i, 'Christmas');
console.log(newstr); // Twas the night before Christmas...
결과보기
'Twas the night before Christmas...'로 출력됩니다.
반응형
'Javascript' 카테고리의 다른 글
repeat() (4) | 2022.08.17 |
---|---|
concat() (5) | 2022.08.17 |
split() (5) | 2022.08.17 |
대/소문자 변경과 공백 제거 (5) | 2022.08.17 |
문자열 결합 / 템플릿 문자열 (4) | 2022.08.17 |
댓글