[Edit]
+
0
-
0

JavaScript - parse file size to bytes (input in: B, KB, MB, GB, TB, PB)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
const EXPRESSION = /^\s*(\d+(?:\.\d+)?)\s?(b|kb|mb|gb|tb|pb|bytes?|kilobytes?|megabytes?|gigabytes?|terabytes?|petabytes?)\s*$/i; const POWERS = { // short long alias b: 1, bytes: 1, byte: 1, kb: 1024, kilobytes: 1024, kilobyte: 1024, mb: 1048576, megabytes: 1048576, megabyte: 1048576, gb: 1073741824, gigabytes: 1073741824, gigabyte: 1073741824, tb: 1099511627776, terabytes: 1099511627776, terabyte: 1099511627776, pb: 1125899906842624, petabytes: 1125899906842624, petabyte: 1125899906842624 }; const findPower = (unit) => { const key = unit.toLowerCase(); return POWERS[key]; }; const parseSize = (text) => { const match = EXPRESSION.exec(text); if (match) { const value = parseFloat(match[1]); const power = findPower(match[2]); return Math.round(value * power); } return NaN; }; // Usage example: // IN BYTES: console.log(parseSize('10.5KB')); // 10752 console.log(parseSize('10.5MB')); // 11010048 console.log(parseSize('10.5 kilobytes')); // 10752 console.log(parseSize('10.5 megabytes')); // 11010048 // Alternatives: // // 1. https://www.npmjs.com/package/bytes (https://github.com/visionmedia/bytes.js) // See also: // // 1. https://dirask.com/snippets/JavaScript-format-size-in-bytes-to-human-readable-KB-MB-GB-TB-PB-jmLNQp // 2. https://dirask.com/snippets/JavaScript-format-size-in-bytes-to-human-readable-KB-MB-GB-TB-PB-jvJOXj // 3. https://dirask.com/snippets/JavaScript-format-size-in-bytes-to-human-readable-KB-MB-GB-TB-PB-pJa8gD
Reset