从字符串中读取特定行?

时间:2013-10-17 00:33:41

标签: javascript jquery html

获得DOM之后,innerHTML的一切都很好,但我不希望将全文放在div中。

function loadXMLDoc()
{
    var xmlhttp;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        var extractedtext;
        extractedtext=xmlhttp.responseText;
        ;
         document.getElementById("myDiv").innerHTML=extractedtext;



        }
    }
    xmlhttp.open("GET","list2.txt",true);
    xmlhttp.send();
    setInterval (loadXMLDoc, 1000);
}

如何在extracttext上获取一系列特定行,考虑到它是一个巨大的txt文件?

1 个答案:

答案 0 :(得分:1)

使用indexOf('\n')计算循环,直到您完成所需的行数

function getLines(haystack, from, toIncluding) {
    var i = 0, j = 0;
    haystack = '\n' + haystack; // makes life easier
    --from;                     // start from "line 1"
    while (from-->0 && i !== -1)
        --toIncluding, i = haystack.indexOf('\n', i + 1);
    if (i === -1) return '';
    j = i;
    while (toIncluding-->0 && j !== -1)
        j = haystack.indexOf('\n', j + 1);
    if (j === -1) j = haystack.length;
    return haystack.slice(i + 1, j);
}

var str = '1\n2\n3\n4';
getLines(str, 2, 3); // "2\n3"
getLines(str, 1, 1); // "1"
getLines(str, 4, 4); // "4"
getLines(str, 1, 4); // "1\n2\n3\n4"
相关问题