Strings in JavaScript are represented in UTF-16 internally, so every character take actually two bytes. So your question is more like "Get bytes length of str in UTF-8".
Hardly you need half of a symbol, so it may cut 198 or 199 bytes.
Here're 2 different solutions:
// direct byte size counting
function cutInUTF8(str, n) {
var len = Math.min(n, str.length);
var i, cs, c = 0, bytes = 0;
for (i = 0; i < len; i++) {
c = str.charCodeAt(i);
cs = 1;
if (c >= 128) cs++;
if (c >= 2048) cs++;
if (c >= 0xD800 && c < 0xDC00) {
c = str.charCodeAt(++i);
if (c >= 0xDC00 && c < 0xE000) {
cs++;
} else {
// you might actually want to throw an error
i--;
}
}
if (n < (bytes += cs)) break;
}
return str.substr(0, i);
}
// using internal functions, but is not very fast due to try/catch
function cutInUTF8(str, n) {
var encoded = unescape(encodeURIComponent(str)).substr(0, n);
while (true) {
try {
str = decodeURIComponent(escape(encoded));
return str;
} catch(e) {
encoded = encoded.substr(0, encoded.length-1);
}
}
}