JavaScript 按行尾字符拆分字符串并读取每一行

JavaScript to split string by end of line character and read each line

本文关键字:字符 一行 读取 字符串 拆分 JavaScript 串并      更新时间:2023-09-26

我需要遍历一个包含多个 eol 字符的大字符串,并阅读这些行中的每一行以查找字符。我本可以执行以下操作,但我觉得它不是很有效,因为这个大字符串中可能有 5000 多个字符。

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

然后作为数组遍历 str

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

还有其他有效的方法吗?

您始终可以使用 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

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

eol是一个 npm 包。在 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) {
  // ...
})

如果您使用的是 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;
  }

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

function findChar(str, char) {
    for (let i = 0; i < str.length; i++) {
        if (str.charAt(i) == char) {
            return i
        }
    }
    return -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(''') 方法可能是最好的。