javascript使用for循环从多个字符串中删除字符

时间:2015-02-22 15:18:29

标签: javascript arrays string for-loop

我正在使用文件阅读器阅读日志文件,然后想要使用javascript进行一些文本操作,以便在我的程序中进一步使用读取数据。到目前为止,我设法按行分割我的输入,但现在我想格式化数组中的特定字符串没有任何反应。这是因为没有全局声明数组吗?基本上我想做一个for循环来检查我的数组中的所有字符串并删除" " (四个空格)出现在我的一些字符串的开头。这是我的代码

$("#draftlog").change(function() {
var logFile = $('#draftlog').get(0).files[0]; 
//gets first file from draftlog
var reader = new FileReader;
reader.readAsText(logFile);
reader.onload = function(e) {
var rawLog = reader.result;
//reads first file from draftlog as text
var re=/\r\n|\n\r|\n|\r/g;
arrayOfLines = rawLog.replace(re,"\n").split("\n");
//splits the text into an array of strings for every new line
for(x=0;x<arrayOfLines.length;x++) {
    arrayOfLines[x].replace(/    /g,'');
}
console.log(arrayOfLines);
};
});

我的输入通常看起来像这样:

Event #: 7952945
Time:    5.2.2015 17:14:54
Players:
    TheDoktorJot
    Arlekin
    Jokulgoblin
    Felo
    Petrolit
    Greyjoy
--> Susti
    themuse1975
    n0sfea

------ FRF ------ 

Pack 1 pick 1:
    Abzan Runemark
    Rakshasa's Disdain
    Reach of Shadows
    Grim Contest
    Aven Skirmisher
    Lotus Path Djinn
    Formless Nurturing
    Tasigur's Cruelty
    Temur Battle Rage
    Return to the Earth
--> Temur Sabertooth
    Fascination
    Jeskai Barricade
    Arcbond
    Rugged Highlands

Pack 1 pick 2:
    Sandblast
    Sultai Runemark
    Jeskai Sage
    Hooded Assassin
    Pressure Point
    Gore Swine
    Whisperer of the Wilds
    Mardu Runemark
    Ambush Krotiq
    Write into Being
    Qarsi High Priest
    Hewed Stone Retainers
    Wardscale Dragon
--> Mastery of the Unseen

1 个答案:

答案 0 :(得分:3)

字符串是不可变的,你必须把它写回来

for(x=0;x<arrayOfLines.length;x++) {
    arrayOfLines[x] = arrayOfLines[x].replace(/    /g,'');
}

您也可以修剪它以删除前导和后续空格

arrayOfLines[x] = arrayOfLines[x].trim();