javascript - insert a variable into regexp

前端 未结 2 1476
鱼传尺愫
鱼传尺愫 2021-01-22 05:50

I have the following which works fine, allowing a form field to be valid if blank or containing the word \"hello\" or passing the other validation...

var re = ne         


        
2条回答
  •  南笙
    南笙 (楼主)
    2021-01-22 05:59

    There are several things wrong in your code.

    • RegExp expects a string, not a regex literal like you pass in the first case. It seems that RegExp is smart enough though and detects that you are passing a regex literal. So your first example works by coincidence and is the same as:

      var re = /^$|^[hello]|^([FG]?\d{5}|\d{5}[AB])$/;
      
    • The / are not part of the expression, they are the delimiters to denote a regex literal, much like quotation marks (') indicate a string literal. Hence, if you pass the expression as string to RegExp, it should not contain /.

    • Since the backslash is the escape character in strings as well, in order to create a literal backslash for the expression you have to escape it: \\.

    • [hello] does not test for for the word hello, it matches either h, e, l or o, thus it is equivalent to [ehlo].

    With all that said, your code should be:

    var i = "hello";
    var re = new RegExp('^$|^'+i+'|^([FG]?\\d{5}|\\d{5}[AB])$');
    

提交回复
热议问题