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

nixgadget picture nixgadget · Nov 4, 2013 · Viewed 22.3k times · Source

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.

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

and then loop through str as an array

I cant really use jquery and can only use simple javascript.

Is there any other efficient way of doing this ?

Answer

fubar picture fubar · Mar 6, 2017

You could always use indexOf and substring to take each line of the string.

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

Edit I didn't see this question was so old before answering. #fail

Edit 2 Fixed code to output final line of text after last newline character - thanks @Blaskovicz