-2

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?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • What exactly are you trying to accomplish here? Are you trying to build a URL from a variable's value? Or are you testing a URL value to see if it matches a particular pattern? – Code-Apprentice Jul 01 '20 at 20:46
  • I suggest you read all of the answers to the linked question instead of just relying on the first one. You might find more information that can help fill in the details you need. – Code-Apprentice Jul 01 '20 at 20:49
  • David isn’t a moderator. Anyway, `new RegExp(replace, "g")` is equivalent to `/regex/g`, as it says in the string. Then `new RegExp("https?:\\/\\/[a-z]{2}w?\\.+= " + mylink + "\\.")` would be equivalent to `/https?:\/\/[a-z]{2}w?\.+= mywebsite\./`. The string `"https?:\\/\\/[a-z]{2}w?\\.+= " + mylink + "\\."` contains the same characters as the equivalent regex. That’s what the [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/RegExp#Parameters) suggests. – Sebastian Simon Jul 01 '20 at 20:53
  • Yes I am trying to build a URL from a variable's value Code-Apprentice. – MostlyBeginner Jul 02 '20 at 10:28
  • Yes I am trying to build a URL from a variable's value @Code-Apprentice. Where the mylink is the variable for the main domain part (without the www. in front and without the .com behind.) The question is how do I get this viarable into the if code? This does not work var mylink = 'mywebsite'; if ( /https?:\/\/[a-z]{2}w?\.+= " + mylink + " \./.test( href ) ) { if ( ! firstSerp ) { firstSerp = this; add_prerender( this, href ); } – MostlyBeginner Jul 02 '20 at 10:41
  • @MostlyBeginner Please reread my comment. Everything you need to know is already there. – Sebastian Simon Jul 02 '20 at 10:58

1 Answers1

0

Regular expressions are intended to be used to check if an existing string matches a pattern or to find a pattern in an existing string. You cannot use them to build a string.

Instead, you should use string concatenation:

const url = 'http://www.' + mywebsite + '.com';

or a string template:

const url = `http://www.${mywebsite}.com`;
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268