function solution(string){
const pp = string.match(/p/gi).length
const yy = string.match(/y/gi).length
return pp <1 && yy <1 ? true : pp === yy ? true : false
}
match 메서드는 null을 반환할 수 있다.'p' 또는 'y'가 전혀 없을 경우 match는 null을 반환하므로, null.length를 호출하려고 하면 에러가 발생하므로 pp나 yy 변수가 에러를 일으키는 상황이 생긴다.
function solution(string) {
const pp = (string.match(/p/gi) || []).length;
const yy = (string.match(/y/gi) || []).length;
return pp === yy;
}
// 표현식의 사용
const reg = /pattern/flags;
const regInstance = new RegExp("pattern", "flags");
// 예제
const str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const regexp = /[A-E]/gi;
const matches_array = str.match(regexp);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']