Search code examples
javascriptregexstringstrip

Remove everything after domain and http in url javascript


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


Solution

  • 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