Regular Expression in JS, 정규표현식 본문

2021 프론트 엔드 로드맵 따라가기/JS

Regular Expression in JS, 정규표현식

알 수 없는 사용자 2021. 6. 12. 18:06

정규표현식은 문자열에서 특정한 문자 조합들을 찾기 위한 패턴을 식으로 표현한 것입니다. ex) 1234 => 정수 4개로 이루어져 있음.

 

따라서 form의 valiation에 자주 쓰이거나, 많은 문자열 데이터 중에서 특정 패턴의 문자열만을 검색하고 싶을 때 주로 이용되죠.

 

exec 메서드의 경우 g플래그가 적용되지 않음에 주의합시다.

 

let regExp;

// 정규표현식 리터럴
regExp = /hello/; // 정확히 hello 라는 문자열만 가져오고 싶은 경우

console.log(regExp);
console.log(regExp.source);

// exec(string) method - 인자로 전달된 문자열 중에서 해당 정규표현식에 맞는 부분을 배열로 리턴, 없을 경우 null
const result1 = regExp.exec("hello devjian");
console.log(result1);
console.log(result1[0]); // founded word
console.log(result1[1]); // index of start
console.log(result1[2]); // input

// test(string) method - 인자로 전달된 문자열 중에서 해당 정규표현식에 맞는 부분이 있으면 true, 없으면 false를 리턴
const result2 = regExp.test("Hello devjian");
console.log(result2);  // false (대문자로 시작하는 Hello이기 때문)

regExp = /hello/i;  // i를 플래그로 넣으면 대소문자를 가리지 않고 검색한다 (insensitive)

const result3 = regExp.test("Hello devjian");
console.log(result3);  // true

regExp = /ello/g;  // g를 플래그로 넣으면 해당 정규표현식에 맞는 모든 단어들을 검색한다 (global)

// String.match(regExp) - 참조하는 문자열이 해당 정규표현식과 일치하는 부분을 배열로 리턴. g플래그를 이용하면 모든 일치하는 모든 부분을 리턴한다.
const result4 = "hello yellow".match(regExp);
console.log(result4); // ["ello", "ello"]

// String.search(regExp) - 참조하는 문자열이 해당 정규표현식과 첫번째로 일치하는 부분의 index를 리턴. 못찾으면 -1.
const result5 = "test yellow".search(regExp);
console.log(result5); // 6

// String.replace(regExp, string) - 참조하는 문자열이 해당 정규표현식과 일치하는 부분을 2번째 인자의 문자열로 교체하고 리턴한다.
const result6 = "hello yello".replace(regExp, "elo");
console.log(result6);
Comments