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.

4
  • Why not just parse that part out? Commented Jul 4, 2012 at 17:02
  • replace www. with a blank ! Commented Jul 4, 2012 at 17:02
  • Whats wrong with indexOf() You can just check if(url.indexOf('youtube.com')){_youtube here_}elseif(url.indexOf('vimeon.com')){_vimeo there_}else{_none of them_} ? Commented Jul 4, 2012 at 17:03
  • Check my answer, it looks for host, not indexOf :) Commented Jul 4, 2012 at 17:13

4 Answers 4

3
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

Sign up to request clarification or add additional context in comments.

Comments

0
    if(domain_name.indexOf("youtube.com") != -1 || domain_name.indexOf("vimeo.com") != -1){
        //...
    }

Comments

0
url = url.toLowerCase();

if (url.indexOf('youtube.com') > -1 || url.indexOf('vimeo.com') > -1) .....

Comments

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.','');

3 Comments

This still includes the www part.
you can remove it , if you want. Updated
But now it won't work if there's no www. So perhaps some www detection code needs to be implemented? This doesn't seem very efficient, although I might be wrong.

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.