I’m creating an input system where a fields maximum value can only be 200 bytes. I am counting the remaining number of bytes by using the following (this method might but up for debate, too!):
var totalBytes = 200;
var $newVal = $(this).val();
var m = encodeURIComponent($newVal).match(/%[89ABab]/g);
var bytesLeft = totalBytes - ($newVal.length + (m ? m.length : 0));
This appears to work well, however if someone were to paste in a large chunk of data, I want to be able to slice the input and only show 200 bytes of it. I guess in psuedo-code that would look something like :
$newText = substrBytes($string, 0, 200);
Any help or guidance would be appreciated.
Edit : Everything going on here is UTF-8 btw 🙂
Edit 2 : I’m aware that I can loop every character and evaluate, I think I was hoping there might be something a little more graceful to take care of this.
Thanks!
A Google search yielded a blog article, complete with a try-it-yourself input box. I’m copying the code here because SO likes definitive answers rather than links, but credit goes to McDowell.