How to check if the input string is a valid Regular expression?

前端 未结 5 688
北荒
北荒 2020-12-08 13:07

How do you check, in JavaScript, if a string is a proper regular expression that will compile?

For example, when you execute the following javascript, it produces a

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-08 13:36

    function isRegExp(regExp){
              try {
                    new RegExp(regExp);
                  } catch(e) {
                    return false
                  }
             return true
        }
    
    ex:
    isRegExp(/@(\w+)/g) = true
    

提交回复
热议问题