D
D
Denis Bukreev2017-02-20 01:21:09
YouTube
Denis Bukreev, 2017-02-20 01:21:09

How to parse a link to a video?

So it goes.
When creating a post, the user in the field simply throws a link from an unknown resource (well, or at least we will limit ourselves to the top of the 5 most famous ones).
What should I do with it so that when the post is shown, the frame already appears?
Determine what kind of service by domain, enter this service into the database, and then, in the template, simply substitute the required HTML?
Or are there better ways?
I remember that VK did not have this feature for a very long time.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2017-02-20
@denisbookreev

I can tell you about YouTube, last year I fiddled with it.
Get youtubeVideoId

/**
* выдергивает videoId из url или embed
* тесты здесь: http://jsfiddle.net/1j5do56g/1/
*
* @param string input
* @returns string youtube video id
*/
function youtubeGetID(input){
    var r = input.replace(/(>|<)/gi,'').split(/(vi\/|v=|\/v\/|youtu\.be\/|\/embed\/)/)
    if(r[2] !== undefined) {
        return r[2].split(/[^0-9a-z_\-]/i)[0]
    } else {
        r = input.match(/^.*(?:(?:youtu\.be\/|v\/|vi\/|u\/\w\/|embed\/)|(?:(?:watch)?\?v(?:i)?=|\&v(?:i)?=))([^#\&\?]*).*/)
        if(r && r[1] !== undefined) {
            return r[1]
        }
        else return input
    }
}

Test: jsfiddle.net/1j5do56g/1
Making a link and using it as src for iframe
// parse and update id
        var youtubeId = youtubeGetID(field.val())
        field.val(youtubeId)

        // update iframe
        var newSrc = 'http://www.youtube.com/embed/' + youtubeId
        var iframe = field.closest('.panel-body').find('iframe')
        iframe.attr('src', newSrc)

Same story with other services. You can look for ready-made solutions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question