Parse a SRT file with jQuery Javascript

前端 未结 3 941
攒了一身酷
攒了一身酷 2021-01-01 02:24

I\'m trying to parse .srt but I get an internal error and I can\'t figure out what is it.

Here is my code:

    var subtitles;
    jQuery         


        
3条回答
  •  长情又很酷
    2021-01-01 02:49

    Here is one problem:

    o = strip(st[1].split(' --> ')[1]);
    

    At this line, when there isn't any ' --> ' to split, the returned length of the array is 1, which errors when you ask for array item 2.

    And here is another:

    subtitles[cont].number = n;
    ....
    

    Neither is the subtitles declared, nor its properties .number, ... etc.

    Update

    Here is a sample that works (switched the jQuery "read srt file" part for the data)

    var data = document.getElementById("data").innerHTML;
    data = data.replace(/>/g,">");
    
    function strip(s) {
        return s.replace(/^\s+|\s+$/g,"");
    }
    srt = data.replace(/\r\n|\r|\n/g, '\n');
    srt = strip(srt);
    var srt_ = srt.split('\n\n');
    var cont = 0;
    var subtitles = [];
    
    for(s in srt_) {
        st = srt_[s].split('\n');
        if(st.length >=2) {
    
            var st2 = st[1].split(' --> ');
            var t = st[2];
    
            if(st.length > 2) {
                for(j=3; j < st.length;j++)
                    t += '\n'+st[j];
            }
            
            subtitles[cont] = { number : st[0],
                                start : st2[0],
                                end : st2[1],
                                text : t
                              }
            
            console.log(subtitles[cont].number + ": " + subtitles[cont].text);
            document.body.innerHTML += subtitles[cont].number + ": " + subtitles[cont].text + "
    "; cont++; } }

提交回复
热议问题