Search code examples
javascriptregexif-statementdetectlegacy

Detect If Variable Is A Pattern


I cannot figure out a way to detect if a variable is a regex. But I also need to figure out if it is an object so I cannot use the typeof(regex) === 'object' and rely on it since it may since the if statement will execute it as if it was a regex. But I would like it to work in legacy browsers too. Any help will be most appreciated.

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

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



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

Solution

  • You can use 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);
    }