Skip to content

Instantly share code, notes, and snippets.

@gullevek
Last active May 20, 2021 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gullevek/b6ab99ddd73ff0b8b8b414d71aa29f1d to your computer and use it in GitHub Desktop.
Save gullevek/b6ab99ddd73ff0b8b8b414d71aa29f1d to your computer and use it in GitHub Desktop.
javascript to convert human readable bytes (eg 10MB) to a number (10,485,760)
/**
* Convert a string with B/K/M/etc into a byte number
* @param {String|Number} bytes Any string with B/K/M/etc
* @return {String|Number} A byte number, or original string as is
*/
function stringByteFormat(bytes)
{
// if anything not string return
if (!(typeof bytes === 'string' || bytes instanceof String)) {
return bytes;
}
// for pow exponent list
let valid_units = 'bkmgtpezy';
// valid string that can be converted
let regex = /([\d.,]*)\s?(eb|pb|tb|gb|mb|kb|e|p|t|g|m|k|b)$/i;
let matches = bytes.match(regex);
// if nothing found, return original input
if (matches !== null) {
// remove all non valid entries outside numbers and .
// convert to float number
let m1 = parseFloat(matches[1].replace(/[^0-9.]/,''));
// only get the FIRST letter from the size, convert it to lower case
let m2 = matches[2].replace(/[^bkmgtpezy]/i, '').charAt(0).toLowerCase();
if (m2) {
// use the position in the valid unit list to do the math conversion
bytes = m1 * Math.pow(1024, valid_units.indexOf(m2));
}
}
return bytes;
}
@gullevek
Copy link
Author

Because there are so many number to human readable bytes, but not a single one for the other way around.

Not if you send anything other in than string or int/float it will fail of course.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment