Splitting a string into lines in Javascript

I recently ran into the question of how to split a string into its component lines using Javascript without knowing beforehand what type of linebreaks were being used. After experimenting with the problem for a while, I finally arrived at the following solution (please note that I haven’t tested this cross-browser, but it works great in Safari/WebKit):

var lines = text.match(/^.*([\n\r]+|$)/gm);

Or the alternate version if you want to ensure that each line ends with a single linebreak rather than potentially have lines with multiple line breaks at their end (for my purposes this didn’t matter, but it might for yours):

var lines = text.match(/^.*((\r\n|\n|\r)|$)/gm);

The code assumes that text is a multiline string, and it utilizes the built-in Javascript String.match() method, which when performed with a regex with the global flag enabled will return an array of matches. The multiline flag makes sure that the regex matches at the beginning of every line, and the alternatives at the end of the regex match one or more linebreaks or the end of the line (if we are on the last line). The ultimate result of which is you split the string into a Javascript array with one line per index with the linebreaks preserved.

If you’re using PHP, there are better ways to split a string into lines, for instance $lines = preg_split('/\r\n|\n|\r/', $mystring); would do it.

Or, if you don’t need to worry about different types of linebreaks, something like $lines = explode('\n', $mystring); should work.

Although in your case, I would use one regex to find the whole segment that you needed to convert into a UL, and then parse only those lines with a second regex (which would result in less messy logic than if you parsed the entire string line-by-line looking for bullets).

Sure; just loop over the resulting array of lines and parse out the variables using split(), more regex, or however else makes sense for your application.

Alternately, you could use replace() with a function for the replacement and an external variable for storing the results as an array or something similar if you wanted to do everything in one pass for some reason.

Note that I removed the extraneous XMLRequest stuff since it was trying and failing to load a non-existent resource. Additionally you had several errors that may have been contributing to your code failing (like line[i] outside of a loop). You are not going to be able to drop this into whatever application you are trying to build, but it should at least provide you with some indication of a workable direction.