user3499381
user3499381

Reputation: 467

javascript - replacing carriage returns in FileReader

I'm reading in an XML file from another website and I need to replace any line breaks that i get in the response with a space, otherwise words will run together.

I tried this...

    function myFunction(xml) {

            var counter = 0;
            var txtFile = new XMLHttpRequest();
            var captionCounter = 0;
            var captionList = new Array();

            var xmlDoc = xml.responseXML;
            var captions = xmlDoc.getElementsByTagName('text');

            for (i = 0; i < captions.length; i++) {
                var x = xmlDoc.getElementsByTagName('text')[i];
                var y = x.childNodes[0];
                var txt = x.getAttribute("start");
                //document.getElementById("captionComment").innerHTML = document.getElementById("captionComment").innerHTML + "<br/>" + txt + " " + y.nodeValue; 
                captionList[i] = new Array(2);
                captionList[i][0] = txt;
                captionList[i][1] = y.nodeValue;
                captionList[i][1] = captionList[i][1].replace(/&quot;/g, '\\"');
                captionList[i][1] = captionList[i][1].replace(/\r\n/g, ' ');

But it doesn't seem to do anything, like it can't see there's a carriage return there. Here is the website I'm loading: https://www.youtube.com/api/timedtext?&v=lo0X2ZdElQ4&lang=en

and although it looks like the caption "I must say I'm very impressed with the way Mary pronounced my name." is on one line, it actually contains a carriage return after the word "way", so I get "wayMary" instead of "way Mary". I saved the code from that page and I can see the carriage return in the file I save, but the javascript doesn't seem to see it for some reason. This of course happens in other places too.

Upvotes: 2

Views: 931

Answers (1)

JstnPwll
JstnPwll

Reputation: 8685

The problem is that you're looking for carriage return + linefeed, and the data appears to have plain carriage returns. Change your replace line to this and it should work:

captionList[i][1] = captionList[i][1].replace(/\r\n/g, ' ').replace(/[\r\n]/g, ' ');

Upvotes: 2

Related Questions