I have a string and start and length with which to extract a substring. Both positions (start and length) are based on the byte offsets in the original UTF8 string.
However, there is a problem:
The start and length are in bytes, so I cannot use "substring". The UTF8 string contains several multi-byte characters. Is there a hyper-efficient way of doing this? (I don't need to decode the bytes...)
Example: var orig = '你好吗?'
The s,e might be 3,3 to extract the second character (好). I'm looking for
var result = orig.substringBytes(3,3);
Help!
Update #1 In C/C++ I would just cast it to a byte array, but not sure if there is an equivalent in javascript. BTW, yes we could parse it into a byte array and parse it back to a string, but it seems that there should be a quick way to cut it at the right place. Imagine that 'orig' is 1000000 characters, and s = 6 bytes and l = 3 bytes.
Update #2 Thanks to zerkms helpful re-direction, I ended up with the following, which does NOT work right - works right for multibyte but messed up for single byte.
function substrBytes(str, start, length)
{
var ch, startIx = 0, endIx = 0, re = '';
for (var i = 0; 0 < str.length; i++)
{
startIx = endIx++;
ch = str.charCodeAt(i);
do {
ch = ch >> 8; // a better way may exist to measure ch len
endIx++;
}
while (ch);
if (endIx > start + length)
{
return re;
}
else if (startIx >= start)
{
re += str[i];
}
}
}
Update #3 I don't think shifting the char code really works. I'm reading two bytes when the correct answer is three... somehow I always forget this. The codepoint is the same for UTF8 and UTF16, but the number of bytes taken up on encoding depends on the encoding!!! So this is not the right way to do this.