Javascript按行尾字符分割字符串并读取每一行

时间:2013-11-04 03:12:53

标签: javascript string split eol

希望我不会复制现有的问题,但我真的找不到任何人在这里提出这个问题。我需要循环一个包含多个eol字符的大字符串,并读取这些行中的每一行以查找字符。我可以完成以下操作,但我觉得它效率不高,因为这个大字符串中可能有超过5000个字符。

var str = largeString.split("\n");

然后将str作为数组循环

我真的不能使用jquery,只能使用简单的javascript。

还有其他有效的方法吗?

6 个答案:

答案 0 :(得分:4)

您始终可以使用indexOfsubstring来获取字符串的每一行。

var input = 'Your large string with multiple new lines...';
var char = '\n';
var i = j = 0;

while ((j = input.indexOf(char, i)) !== -1) {
  console.log(input.substring(i, j));
  i = j + 1;
}

console.log(input.substring(i));

编辑在回答之前,我没有看到这个问题已经过时了。 #fail

编辑2 修复了在最后一个换行符之后输出最后一行文字的代码 - 谢谢@Blaskovicz

答案 1 :(得分:1)

如果您使用的是NodeJS,并且有较大的字符串来逐行处理,那么这对我有用...

const Readable = require('stream').Readable
const readline = require('readline')

promiseToProcess(aLongStringWithNewlines) {
    //Create a stream from the input string
    let aStream = new Readable();
    aStream.push(aLongStringWithNewlines);
    aStream.push(null);  //This tells the reader of the stream, you have reached the end

    //Now read from the stream, line by line
    let readlineStream = readline.createInterface({
      input: aStream,
      crlfDelay: Infinity
    });

    readlineStream.on('line', (input) => {
      //Each line will be called-back here, do what you want with it...
      //Like parse it, grep it, store it in a DB, etc
    });

    let promise = new Promise((resolve, reject) => {
      readlineStream.on('close', () => {
        //When all lines of the string/stream are processed, this will be called
        resolve("All lines processed");
      });
    });

    //Give the caller a chance to process the results when they are ready
    return promise;
  }

答案 2 :(得分:0)

您可以手动逐个字符地阅读它,并在获得换行符时调用处理程序。就CPU使用率而言,它不太可能更有效,但可能会占用更少的内存。但是,只要字符串小于几MB,就没关系。

答案 3 :(得分:0)

5000对于现代JavaScript引擎来说似乎并不那么激烈。当然,这取决于你在每次迭代中做了什么。为清楚起见,我建议您使用eol.split[].forEach

eol is an npm package。在Node.js和CommonJS中,您可以npm install eolrequire。在ES6捆绑包中,您可以import。否则通过<script> eol 加载全局

// Require if using Node.js or CommonJS
const eol = require("eol")

// Split text into lines and iterate over each line like this
let lines = eol.split(text)
lines.forEach(function(line) {
  // ...
})

答案 4 :(得分:0)

像这样。

function findChar(str, char) {
    for (let i = 0; i < str.length; i++) {
        if (str.charAt(i) == char) {
            return i
        }
    }
    return -1
}

答案 5 :(得分:-1)

所以,你知道怎么做,你只是确保没有更好的方法吗?好吧,我不得不说你提到的方式就是这样。虽然您可能希望查找正则表达式匹配,但如果您要查找按特定字符拆分的特定文本。可以找到JS Regex参考Here

如果您知道如何设置文本,这将非常有用,类似于

var large_str = "[important text here] somethign something something something [more important text]"
var matches = large_str.match(\[([a-zA-Z\s]+)\])
for(var i = 0;i<matches.length;i++){
   var match = matches[i];
   //Do something with the text
}

否则,是的,带循环的large_str.split('\ n')方法可能是最好的。