7

我需要遍历一个带有几个 eol 字符的大字符串,并读取这些行中的每一行以查找字符。我本可以执行以下操作,但我觉得它效率不高,因为这个大字符串中可能有超过 5000 个字符。

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

然后将 str 作为数组循环

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

有没有其他有效的方法来做到这一点?

4

6 回答 6

4

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

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));

编辑在回答之前我没有看到这个问题太老了。#失败

编辑 2固定代码以在最后一个换行符之后输出最后一行文本 - 感谢@Blaskovicz

于 2017-03-06T05:04:52.790 回答
2

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

eol是一个 npm 包npm install eol在 Node.js和CommonJS 中,你可以require做到。在 ES6 捆绑器中,您可以import. 否则加载 via<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) {
  // ...
})
于 2017-06-26T00:13:21.323 回答
2

如果您使用的是 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;
  }
于 2019-08-09T15:37:49.633 回答
0

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

于 2016-11-28T12:18:52.033 回答
0
function findChar(str, char) {
    for (let i = 0; i < str.length; i++) {
        if (str.charAt(i) == char) {
            return i
        }
    }
    return -1
}
于 2021-06-01T03:11:22.670 回答
-1

所以,你知道怎么做,你只是确保没有更好的方法吗?好吧,我不得不说你提到的方式就是这样。虽然如果您正在寻找由某些字符分割的某些文本,您可能想要查找正则表达式匹配。可以在此处找到 JS 正则表达式参考

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

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') 方法可能是最好的。

于 2013-11-04T03:26:16.227 回答