0

I want to create a regex that parse only links that complies to the current domain. I want to know if there is something like {hostname} that I can use inside a Javascript regex object so it will lock the search only to those links that are for the current page specific domain.

For example: if the domain is www.domain.com, it will search links only links that start with that specific domain. if the domain is anotherdomain.com, it will search only links that start with that specific domain. My regex is more complex, but I would like to be able to put some kind of global variable that will be replaced with the current domain.

Liron Harel
  • 10,819
  • 26
  • 118
  • 217
  • Do you have any code you've written? The current answer is "no". – Polyov Jul 15 '12 at 17:36
  • No. But can you share more details of what you are trying to do? Why do you need a regex and regex only? I have a feeling that this can be solved in a simpler way. –  Jul 15 '12 at 17:39

2 Answers2

2

You can retrieve the hostname of the current page via the Location object :

var hostname = window.location.hostname;

And then you can compose your regex using that variable by concatenating it into your regex :

var re = new RegExp("<start of your regex>" + hostname + "<end of your regex>");
joelrobichaud
  • 665
  • 4
  • 19
2

You can get the hostname from window.location.hostname.

Then, you will want to escape potential special characters in a hostname.

A hostname will usually include . which is a special character in regular expressions, and it can certainly also contain - which can be a special character.

Probably best to engage in defensive programming and escape everything that might be special characters in regular expressions even though a lot of them shouldn't actually ever appear. From Escape string for use in Javascript regex you can use this function:

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

And then you can do this:

var regexpFragment = escapeRegExp(window.location.hostname);
Community
  • 1
  • 1
Trott
  • 66,479
  • 23
  • 173
  • 212