Converting Youtube Data API V3 video duration format to seconds in JavaScript/Node.js

后端 未结 15 2036
北海茫月
北海茫月 2020-12-05 07:09

I\'m trying to convert ISO 8601 string to seconds in JS/Node. The best I could come up with was:

function convert_time(duration) {
    var a = duration.match         


        
15条回答
  •  一向
    一向 (楼主)
    2020-12-05 07:36

    Assuming the input is valid, we can use the regex exec method to iterate on the string and extract the group sequentially:

    const YOUTUBE_TIME_RE = /(\d+)([HMS])/g;
    const YOUTUBE_TIME_UNITS = {
        'H': 3600,
        'M': 60,
        'S': 1
    }
    
    /**
     * Returns the # of seconds in a youtube time string
     */
    function parseYoutubeDate(date: string): number {
        let ret = 0;
        let match: RegExpExecArray;
        while (match = YOUTUBE_TIME_RE.exec(date)) {
            ret += (YOUTUBE_TIME_UNITS[match[2]]) * Number(match[1]);
        }
        return ret;
    }
    

提交回复
热议问题