How do I get the YouTube video ID from a URL?

前端 未结 30 2414
北恋
北恋 2020-11-22 03:06

I want to get the v=id from YouTube’s URL with JavaScript (no jQuery, pure JavaScript).

Example YouTube URL formats

http://www.youtube.c

30条回答
  •  梦毁少年i
    2020-11-22 03:30

    If someone needs the perfect function in Kotlin to save their time. Just hoping this helps

    fun extractYTId(ytUrl: String?): String? {
        var vId: String? = null
        val pattern = Pattern.compile(
            "^https?://.*(?:youtu.be/|v/|u/\\w/|embed/|watch?v=)([^#&?]*).*$",
            Pattern.CASE_INSENSITIVE
        )
        val matcher = pattern.matcher(ytUrl)
        if (matcher.matches()) {
            vId = matcher.group(1)
        }
        return vId
    }
    

提交回复
热议问题