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.

2
  • Do you have any code you've written? The current answer is "no". Commented Jul 15, 2012 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. Commented Jul 15, 2012 at 17:39

2 Answers 2

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>");
Sign up to request clarification or add additional context in comments.

Comments

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);

1 Comment

+1 for escaping special characters, I forgot to mention that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.