1

I need to process URLs with JS and find out if they belong to youtube.com, vimeo.com or none of them. How do I do that?

I found this question How to get Domain name from URL using jquery..?, but it keeps 'http://www.' part if it's included in the URL.

EDIT: People suggesting the indexOf solution: what if there's a youtube.com inside the URL path? Is this even possible? As in www.example.com/?article=why_youtube.com_is_the_best? This question Can . (period) be part of the path part of an URL? seems to indicate that this is a valid URL.

Community
  • 1
  • 1
Stas Bichenko
  • 13,013
  • 8
  • 45
  • 83

4 Answers4

2
var a = 'http://www.youtube.com/somevideo/vimeo';
var b = 'http://vimeo.com/somevideo/youtube';

var test = checkUrl(b);
console.log(test); //prints Vimeo


function checkUrl(test_url) {
    var testLoc = document.createElement('a');
        testLoc.href = test_url.toLowerCase();
    url = testLoc.hostname;
    var what;
    if (url.indexOf('youtube.com') !== -1) {
        what='Youtube';
    }else if (url.indexOf('vimeo.com') !== -1) {
        what='Vimeo';
    }else{
        what='None';
    }
    return what;
}

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
0
url = url.toLowerCase();

if (url.indexOf('youtube.com') > -1 || url.indexOf('vimeo.com') > -1) .....
Jashwant
  • 28,410
  • 16
  • 70
  • 105
E.J. Brennan
  • 45,870
  • 7
  • 88
  • 116
0
    if(domain_name.indexOf("youtube.com") != -1 || domain_name.indexOf("vimeo.com") != -1){
        //...
    }
Vilius Gaidelis
  • 430
  • 5
  • 14
0
var url = 'http://www.youtube.com/myurl/thevideo/';
var host = $('<a>click</a>').attr('href',url)[0].host;

if(host === 'www.youtube.com'){

}

EDIT:

If you want to remove www, use this

var host = $('<a>click</a>').attr('href',url)[0].host.replace('www.','');
Jashwant
  • 28,410
  • 16
  • 70
  • 105