簡體   English   中英

JavaScript 按行尾字符拆分字符串並讀取每一行

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

我需要遍歷一個包含多個 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));

編輯我沒有看到這個問題在回答之前已經過時了。 #失敗

編輯2固定代碼輸出最后一個換行符后的最后一行文字 - 謝謝@Blaskovicz

您可以手動逐個字符地閱讀它,並在獲得換行符時調用處理程序。 就CPU使用率而言,它不太可能更有效,但可能會占用更少的內存。 但是,只要字符串小於幾MB,就沒關系。

對於現代JavaScript引擎來說,5000似乎並不那么激烈。 當然,這取決於你在每次迭代中做了什么。 為清楚起見,我建議使用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;
  }
function findChar(str, char) {
    for (let i = 0; i < str.length; i++) {
        if (str.charAt(i) == char) {
            return i
        }
    }
    return -1
}

所以,你知道怎么做,你只是確保沒有更好的方法去做嗎? 好吧,我不得不說你提到的方式就是這樣。 雖然您可能希望查找正則表達式匹配,但如果您要查找按特定字符拆分的特定文本。 可以在此處找到JS Regex參考

如果你知道文本將如何設置,這將是有用的,類似於

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM