title: String length in bytes in JavaScript
body: <p>In my JavaScript code I need to compose a message to server in this format:</p>
  
  <pre><code>&lt;size in bytes&gt;CRLF
  &lt;data&gt;CRLF
  </code></pre>
  
  <p>Example:</p>
  
  <pre><code>3
  foo
  </code></pre>
  
  <p>The data may contain unicode characters. I need to send them as UTF-8.</p>
  
  <p>I'm looking for the most cross-browser way to calculate the length of the string in bytes in JavaScript.</p>
  
  <p>I've tried this to compose my payload:</p>
  
  <pre><code>return unescape(encodeURIComponent(str)).length + "\n" + str + "\n"
  </code></pre>
  
  <p>But it does not give me accurate results for the older browsers (or, maybe the strings in those browsers in UTF-16?).</p>
  
  <p>Any clues?</p>
  
  <p><em>Update:</em></p>
  
  <p>Example: length in bytes of the string <code>ЭЭХ! Naïve?</code> in UTF-8 is 15 bytes, but some browsers report 23 bytes instead.</p>