카테고리 없음
정규식표현(RegExp)02 - 메서드 test,replace,match / 플래그
maggieH
2021. 6. 2. 11:49
1.자주사용되는 정규식표현 메서드
test | `정규식.test(문자열)` | 일치여부(boolean)반환
match | `문자열.match(정규식) `| 일치하는 문자의배열(array)반환
replace | `문자열.replace(정규식, 대체문자)` | 일치하는 문자를 대체
2.플래그
g | 모든 문자와 여러 줄 일치(global)
i | 영어 대소문자를 구분 않고 일치(insensitive, ignore case)
m | 여러 줄 일치(multi line)
u | 유니코드(unicode)
y | lastIndex 속성으로 지정된 인덱스에서만 1회 일치(sticky)
const str = `
010-1234-1234
themain@mail.com
https://www.naver.com
The buick brown fox jumps over the lazy dog
aaabbbccddd
`;
const regexp = /fox/gi;
//regexp.test(str)
//console.log(regexp.test(str));
//regexp.replace(str)
//replace 메서드는 원본 손상을 하지 않는 메서드임으로
//str을 AAA로 변경시 const > let, str = str.replace(a,b)구문으로 바꿔줄것
console.log(str.replace(regexp, "AAA"));
console.log(str);
match 메서드와 플래그 예시
const str = `
010-1234-1234
themain@mail.com
https://www.naver.com
The buick brown fox jumps over the lazy dog
aaabbbccddd
`;
//1번째 배열만반환
// const regexp = /the/;
// const regexp = /the/gi;
// console.log(str.match(regexp));
//상단 식축소 :console.log(str.match(/the/gi));
// \은 이스케이프 문자로 문자로 해석되라는 의미
//console.log(str.match(/\./gi));
//$:달러사인 앞쪽 '\.(문자열로해석되는 .)'끝나는 부분에 있는지,
//gim의 m : 여러줄 일치 (문자데이터 내부 줄바꿈 되어있는 부분들해석 하겠다는 의미, 전체줄 해석x)
console.log(str.match(/\.$/gim));