Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a need to loop through a large string with several eol characters and read each of these lines looking for characters. I could've 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?

like image 335
nixgadget Avatar asked Nov 04 '13 03:11

nixgadget


1 Answers

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

like image 113
fubar Avatar answered Oct 02 '22 23:10

fubar