2017-09-06 19 views
0

변수가 정규식인지 감지하는 방법을 찾을 수 없습니다. 하지만 if 문이 정규식 인 것처럼 그것을 실행할 것이기 때문에 나는 그것이 typeof(regex) === 'object'을 사용할 수 없기 때문에 객체인지를 알아야합니다. 하지만 레거시 브라우저에서도 작동하고 싶습니다. 어떤 도움을 주시면 감사하겠습니다.변수가 패턴 인 경우 감지

var regex= /^[a-z]+$/; 

//...Some code that could alter the regex variable to become an object variable. 



if (typeof(regex) === 'object') { 
    console.log(true); 
} 

답변

0

당신은 instanceOf

var regex= /^[a-z]+$/; 
 

 
//...Some code that could alter the regex variable to become an object variable. 
 

 

 

 
if (regex instanceof RegExp) { 
 
    console.log(true); 
 
}

0

이 작업을 수행 할 수있는 방법이 있습니다 사용할 수 있습니다, 그들은 다음과 같습니다

var regex= /^[a-z]+$/; 
 

 
// constructor name, a string 
 
// Doesn't work in IE 
 
console.log(regex.constructor.name === "RegExp"); // true 
 
// instanceof, a boolean 
 
console.log(regex instanceof RegExp); // true 
 
// constructor, a constructor 
 
console.log(regex.constructor == RegExp); // true

+0

첫 번째 것은 IE에서 작동하지 않습니다. 함수 이름을 테스트하지 마십시오. – Bergi

+0

@Bergi 그래서 내가 다른 방법들을 언급 했지. –

+0

하지만 왜 모든 것을 언급합니까? 그것은 단지 누군가가 대답을 읽는 것이 나쁜 습관을 고취시킬 기회를 증가시킵니다 (특히 처음에 언급 한 것처럼). – Bergi