Passing regex modifier options to RegExp object

后端 未结 6 1795
陌清茗
陌清茗 2020-11-27 06:56

I am trying to create something similar to this:

var regexp_loc = /e/i;

except I want the regexp to be dependent on a string, so I tried to

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 07:27

    You should also remember to watch out for escape characters within a string...

    For example if you wished to detect for a single number \d{1} and you did this...

    var pattern = "\d{1}";
    var re = new RegExp(pattern);
    
    re.exec("1"); // fail! :(
    

    that would fail as the initial \ is an escape character, you would need to "escape the escape", like so...

    var pattern = "\\d{1}" // <-- spot the extra '\'
    var re = new RegExp(pattern);
    
    re.exec("1"); // success! :D
    

提交回复
热议问题