javascript Javascript按行尾字符拆分字符串并读取每一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19761086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript to split string by end of line character and read each line
提问by nixgadget
Hopefully Im not duplicating an existing question but I couldn't really find anyone having this question here. I have a need to loop through a large string with several eol characters and read each of these lines looking for characters. I couldve done the following but I feel that its not very efficient as there could be more than 5000 characters in this large string.
希望我没有重复现有的问题,但我真的找不到在这里有这个问题的人。我需要遍历一个包含多个 eol 字符的大字符串并读取这些行中的每一行以查找字符。我可以完成以下操作,但我觉得它不是很有效,因为这个大字符串中可能有超过 5000 个字符。
var str = largeString.split("\n");
and then loop through str as an array
然后将 str 作为数组循环
I cant really use jquery and can only use simple javascript.
我不能真正使用 jquery,只能使用简单的 javascript。
Is there any other efficient way of doing this ?
有没有其他有效的方法来做到这一点?
回答by fubar
You could always use indexOf
and substring
to take each line of the string.
您始终可以使用indexOf
和substring
来获取字符串的每一行。
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));
EditI didn't see this question was so old before answering. #fail
编辑在回答之前我没有看到这个问题这么老。#失败
Edit 2Fixed code to output final line of text after last newline character - thanks @Blaskovicz
编辑 2固定代码以在最后一个换行符之后输出最后一行文本 - 感谢 @Blaskovicz
回答by Sagan
If you are using NodeJS, and have a large string to process line-by-line, this worked for me...
如果您使用的是 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;
}
回答by user3096439
You could read it character by character manually and call a handler when you get a newline. It is unlikely to be more efficient in terms of CPU usage but will likely take up less memory. However, as long as the string is less than a few MBs, it should not matter.
您可以手动逐个字符地读取它,并在获得换行符时调用处理程序。就 CPU 使用而言,它不太可能更有效,但可能会占用更少的内存。但是,只要字符串小于几 MB 就没有关系。
回答by ryanve
5000 doesn't seem that intense for a modern JavaScript engine. Of course it depends on what you do on each iteration too. For clarity I recommend using eol.split
and [].forEach
.
5000 对于现代 JavaScript 引擎来说似乎并不那么激烈。当然,这也取决于您在每次迭代中的操作。为清楚起见,我建议使用eol.split
和[].forEach
。
eol
is an npm package. In Node.js and CommonJS you can npm install eol
and require
it. In ES6 bundlers you can import
. Otherwise loaded via <script>
eol
is global
eol
是一个 npm 包。在 Node.js 和 CommonJS 中,你可以npm install eol
和require
它。在 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) {
// ...
})
回答by Jhecht
So, you know how to do it, you're just making sure there's no better way to do it? Well, I'd have to say the way you've mentioned is exactly it. Although you may want to look up a regex match if you're looking for certain text split by certain characters. A JS Regex Reference can be found Here
所以,你知道怎么做,你只是确保没有更好的方法来做到这一点?嗯,我不得不说你提到的方式正是它。尽管如果您要查找由某些字符分割的某些文本,您可能需要查找正则表达式匹配项。可以在此处找到 JS 正则表达式参考
This would be useful if you know how the text is going to be setup, something akin to
如果您知道文本将如何设置,这将很有用,类似于
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
}
Otherwise, yes, the large_str.split('\n') method with a loop is probably best.
否则,是的,带循环的 large_str.split('\n') 方法可能是最好的。