Passing regex modifier options to RegExp object

后端 未结 6 1777
陌清茗
陌清茗 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条回答
  •  粉色の甜心
    2020-11-27 07:23

    Want to share an example here:

    I want to replace a string like: hi[var1][var2] to hi[newVar][var2]. and var1 are dynamic generated in the page.

    so I had to use:

    var regex = new RegExp("\\\\["+var1+"\\\\]",'ig');
    mystring.replace(regex,'[newVar]');
    

    This works pretty good to me. in case anyone need this like me. The reason I have to go with [] is var1 might be a very easy pattern itself, adding the [] would be much accurate.

提交回复
热议问题