How to add a variable to a regex checking for a URL?

不想你离开。 提交于 2020-07-04 04:23:15

问题


I have this part of a function which is running perfectly:

if(/https?:\/\/[a-z]{2}w?\.mywebsite\./.test(href)){
  if(!firstSerp){
    firstSerp = this;
    add_prerender(this, href);
  }
}

As you can see mywebsite is hard-coded. What I want is to put a variable there instead.

So it would look like this:

var mylink = 'mywebsite';

if(/https?:\/\/[a-z]{2}w?\.+= mylink\./.test(href)){}

One of the users suggested I look at How do you use a variable in a regular expression?

var replace = "regex";
var re = new RegExp(replace,"g");

But I have difficulties understanding how that would apply to my example.

Could you please help me solve this?

来源:https://stackoverflow.com/questions/62683766/how-to-add-a-variable-to-a-regex-checking-for-a-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!