javascript - 替换 FileReader 中的回车 returns
javascript - replacing carriage returns in FileReader
我正在从另一个网站读取 XML 文件,我需要用 space 替换响应中的任何换行符,否则文字会 运行一起。
我试过了...
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(/"/g, '\"');
captionList[i][1] = captionList[i][1].replace(/\r\n/g, ' ');
但它好像什么也没做,好像看不到那里有马车return。这是我正在加载的网站:https://www.youtube.com/api/timedtext?&v=lo0X2ZdElQ4&lang=en
虽然标题 "I must say I'm very impressed with the way Mary pronounced my name." 看起来在一行,但它实际上在单词 "way" 之后包含一个回车符 return,所以我得到的是 "wayMary" "way Mary"。我保存了那个页面的代码,我可以在我保存的文件中看到回车 return,但是 javascript 由于某种原因似乎没有看到它。这当然也发生在其他地方。
问题是您正在寻找 carriage return + linefeed
,而数据似乎有普通回车 returns。将您的替换行更改为此,它应该可以工作:
captionList[i][1] = captionList[i][1].replace(/\r\n/g, ' ').replace(/[\r\n]/g, ' ');
我正在从另一个网站读取 XML 文件,我需要用 space 替换响应中的任何换行符,否则文字会 运行一起。
我试过了...
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(/"/g, '\"');
captionList[i][1] = captionList[i][1].replace(/\r\n/g, ' ');
但它好像什么也没做,好像看不到那里有马车return。这是我正在加载的网站:https://www.youtube.com/api/timedtext?&v=lo0X2ZdElQ4&lang=en
虽然标题 "I must say I'm very impressed with the way Mary pronounced my name." 看起来在一行,但它实际上在单词 "way" 之后包含一个回车符 return,所以我得到的是 "wayMary" "way Mary"。我保存了那个页面的代码,我可以在我保存的文件中看到回车 return,但是 javascript 由于某种原因似乎没有看到它。这当然也发生在其他地方。
问题是您正在寻找 carriage return + linefeed
,而数据似乎有普通回车 returns。将您的替换行更改为此,它应该可以工作:
captionList[i][1] = captionList[i][1].replace(/\r\n/g, ' ').replace(/[\r\n]/g, ' ');