Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Depends what you mean by a line. For simple number of newlines, Robusto's answer is fine.</p> <p>If you want to know how many <em>rows</em> of CSV data that represents, things may be a little more difficult, as a CSV field may itself contain a newline:</p> <pre><code>field1,"field two",field3 </code></pre> <p>...is one row, at least in CSV as defined by <a href="http://tools.ietf.org/html/rfc4180" rel="noreferrer">RFC4180</a>. (It's one of the aggravating features of CSV that there are so many non-standard variants; the RFC itself was very late to the game.)</p> <p>So if you need to cope with that case you'll have to essentially parse each field.</p> <p>A field can be raw, or (necessarily if it contains <code>\n</code> or <code>,</code>) quoted, with <code>"</code> represented as double quotes. So a regex for one field would be:</p> <pre><code>"([^"]|"")*"|[^,\n]* </code></pre> <p>and so for a whole row (assuming it is not empty):</p> <pre><code>("([^"]|"")*"|[^,\n]*)(,("([^"]|"")*"|[^,\n]*))*\n </code></pre> <p>and to get the number of those:</p> <pre><code>var rowsn= csv.match(/(?:"(?:[^"]|"")*"|[^,\n]*)(?:,(?:"(?:[^"]|"")*"|[^,\n]*))*\n/g).length; </code></pre> <p>If you are lucky enough to be dealing with a variant of CSV that complies with RFC4180's recommendation that there are no <code>"</code> characters in unquoted fields, you can make this a bit more readable. Split on newlines as before and count the number of <code>"</code> characters in each line. If it's an even number, you have a complete line; if it's an odd number you've got a split.</p> <pre><code>var lines= csv.split('\n'); for (var i= lines.length; i--&gt;0;) if (lines[i].match(/"/g).length%2===1) lines.splice(i-1, 2, lines[i-1]+lines[i]); var rowsn= lines.length; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload