5

I have the full url in a javascript variable and I want to strip it down to the bare url.

For example:

https://www.google.com/hello/hi.php, http://youtube.com

strip down to:

www.google.com, youtube.com

How would I do this in javascript?

Thanks

This is not similar to the other links as I am doing this within a chrome extension, therefore the only way to get the url is using the chrome extension api which only provides the full url. As such I need to strip the full url

kabeersvohra
  • 971
  • 1
  • 10
  • 27

2 Answers2

4

You can try this:

\/\/([^\/,\s]+\.[^\/,\s]+?)(?=\/|,|\s|$|\?|#)

Regex live here.


Live JavaScript sample:

var regex = /\/\/([^\/,\s]+\.[^\/,\s]+?)(?=\/|,|\s|$|\?|#)/g;

var input = "https://www.google.com/hello/hi.php, http://youtube.com,"
          + "http://test.net#jump or http://google.com?q=test";

while (match = regex.exec(input)) {
    document.write(match[1] + "<br/>");
};

Hope it helps

  • I have no idea why this has been downvoted so much, it works perfectly and is exactly what I need. Thanks. I will accept it in 5 mins when I am able to – kabeersvohra Aug 11 '15 at 12:44
  • @KVohra95. It was downvoted because my first attempt of solving was really bad... –  Aug 11 '15 at 12:45
  • 1
    @Jonny5. Thank you for that. I've updated. –  Aug 11 '15 at 13:06
  • im struggling on implementing this regex in javascript. I know how to do it in php but would you be able to help? How would i apply this regex to a string in javascript and return the part of the string that is valid? Thanks – kabeersvohra Aug 11 '15 at 14:28
  • @KVohra95. I've updated with a javascript example. Hope it helps. –  Aug 11 '15 at 15:05
  • Yes! Perfect, thank you :) – kabeersvohra Aug 11 '15 at 15:11
3

Use the global window.location.hostname variable, and it will give you this information.

meskobalazs
  • 14,510
  • 2
  • 33
  • 55
  • this would be fine but I am doing this via a chrome extension and therefore I needed to strip the full url since I do not have access to window.location.hostname. Thanks for the suggestion however – kabeersvohra Aug 11 '15 at 12:45
  • Next time try to specify your dev environment in the question. Then you won't receive a bunch of close flags. – meskobalazs Aug 11 '15 at 12:48