JavaScript Converting Byte To KB, MB

How To Convert Bytes to KB, MB, GB, TB Format in JavaScript. This function Converting bytes to human readable values Kilobyte, Megabyte, Gigabyte, Terabyte

Demo Byte Converter
Demo

Javascript Size Bytes Converting Function

JavaScript
const byte_format = bytes => {
    bytes = bytes.toString().replace(/[^0-9.]/g, '');
    let sizes = ["B", "KB", "MB", "GB", "TB"];
    bytes = parseInt(bytes);
    if (bytes <= 0 || isNaN(bytes)) return "0 B";
    let i = Math.floor(Math.log(bytes) / Math.log(1024));
    return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};

Usage size convert

HTML
byte <input type="number" id="byte" value="1024">
<button id="convert-byte">Convert</button>
<div id="preview-size"></div>

<script>
document.getElementById("convert-byte").onclick = function(){
  let byte = document.getElementById("byte").value;
  let result = byte_format(byte);
  document.getElementById("preview-size").innerHTML= result
}
</script>