JSFiddle - React, Tailwind, and code Playground

by Alexey Demin

HTML

<div data-max-file-size="1"></div>
<div data-max-file-size="0.5 Mb"></div>
<div data-max-file-size="1.5 Mb"></div>
<div data-max-file-size="1GB"></div>
<div data-max-file-size="10 Kb"></div>
<div data-max-file-size="1024"></div>
<div data-max-file-size="10240 B"></div>
<div data-max-file-size=""></div>
<div data-max-file-size="1232.95"></div>

JavaScript

console.clear();

$("div").each(function(idx, itm) {
  if (itm.dataset.maxFileSize != "undefined" && itm.dataset.maxFileSize.length > 0) {
  	var fSize = itm.dataset.maxFileSize;
    console.log("value %o converted to %o", fSize, decodeByteString(fSize));
  }
});

function decodeByteString(formatedByteString) {

  var sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
    	re = new RegExp('^(?<qty>[0-9]+[.]?[0-9]*) *(?:(?<size>(?:' + sizes.join('|') + ')))?$', 'i'),
      str = formatedByteString + "".trim().toUpperCase();
  
  if(str === "" || re.test(str) === false){
  		console.log("test of %o failed", str);
  		return 0;
  }
      
  var	reGrp = re.exec(str).groups;

  var size = reGrp.size == undefined ? sizes[0] : reGrp.size, 
  		qty = size === sizes[0] ? parseInt(reGrp.qty) : parseFloat(reGrp.qty, 2),
      pow = sizes.indexOf(size.toUpperCase());
  console.log("str: %o,size: %o, qty: %o, pow: %o", str, size, qty, pow);    
  return qty * Math.pow(1024, pow);
}