I am looking for some guidance and optimization pointers for my custom JavaScript function which counts the bytes in a string rather than just chars. The website uses UTF-8 and I am looking to maintain IE8 compatibility.
/**
* Count bytes in string
*
* Count and return the number of bytes in a given string
*
* @access public
* @param string
* @return int
*/
function getByteLen(normal_val)
{
// Force string type
normal_val = String(normal_val);
// Split original string into array
var normal_pieces = normal_val.split('');
// Get length of original array
var normal_length = normal_pieces.length;
// Declare array for encoded normal array
var encoded_pieces = new Array();
// Declare array for individual byte pieces
var byte_pieces = new Array();
// Loop through normal pieces and convert to URL friendly format
for(var i = 0; i <= normal_length; i++)
{
if(normal_pieces[i] && normal_pieces[i] != '')
{
encoded_pieces[i] = encodeURI(normal_pieces[i]);
}
}
// Get length of encoded array
var encoded_length = encoded_pieces.length;
// Loop through encoded array
// Scan individual items for a %
// Split on % and add to byte array
// If no % exists then add to byte array
for(var i = 0; i <= encoded_length; i++)
{
if(encoded_pieces[i] && encoded_pieces[i] != '')
{
// % exists
if(encoded_pieces[i].indexOf('%') != -1)
{
// Split on %
var split_code = encoded_pieces[i].split('%');
// Get length
var split_length = split_code.length;
// Loop through pieces
for(var j = 0; j <= split_length; j++)
{
if(split_code[j] && split_code[j] != '')
{
// Push to byte array
byte_pieces.push(split_code[j]);
}
}
}
else
{
// No percent
// Push to byte array
byte_pieces.push(encoded_pieces[i]);
}
}
}
// Array length is the number of bytes in string
var byte_length = byte_pieces.length;
return byte_length;
}