Search code examples
javascripthtmlarraysregexpre

Putting content from <pre> into array using Javascript


We have report pages that append a <pre> at the bottom of pages that lists information line by line.

Example:

<pre>
  Site Report Info
  This is where any error will appear as a query string of numbers: 938109283091238109281092
  This is where the account ID will be.
  This is where the account reference pin will be.
  So on...
  So on...
  So on...
  So on...
  So on...
</pre>

Using javascript or jquery, perhaps regex, how can I place all of this into one array where each line is an array element? I assume regex, since the way to determine the lines is by identifying line breaks \n ?


Solution

  • var lines = $('pre').text().split('\n') should do the trick.

    You don't need to use jQuery to get the text, of course, but if you're doing web programming, jQuery is pretty ubiquitous.

    You may also want to trim the results to get rid of extra whitespace (or not, depending on your application):

    var lines = $('pre').text().split('\n').map(function(l) { return l.trim(); });