var s = 'hello 1 world|hello -2 world|hello 2 world record|hello 10 world|hello 11.34 world|hello 12 world|zz 123\'456,01 aa|zz 123,456.01 bb|zz 123.456,2 aa|zz 1234.0001 aa|zz 123456 aa|zz 123.456 aa', list, pre, heading; /* list = s.split('|'); list.sort(function(a, b) { return a > b ? 1 : -1; }); heading = document.createElement('h1'); heading.innerHTML = 'simple Sorting'; document.body.appendChild(heading); pre = document.createElement('pre'); pre.innerHTML = list.join("\n"); document.body.appendChild(pre); document.body.appendChild(document.createElement('hr')); */ function padNumbers(string, length) { if (!length) { length = 10; } return string.replace(/(\d+(\S\d+)*)/g, function(m) { var delimiter, decimalLength; //console.log('------------------------------'); //console.log(m); // preserve decimal delimiter m = m.replace(/(\D)(\d+)$/, function(m, delim, num) { delimiter = delim; decimalLength = num.length; return '###' + num; }); // if decimal delimiter occurs multiple times // it is not a decimal delimiter, but thousand delimiter if (delimiter && m.indexOf(delimiter) > -1) { m = m.replace('###', ''); } else { // TODO: decide what to do with decimals // that are 3-accurate - might be german thousand-delim } // remove thousand delimiters m = m.replace(/[^0-9#]/g, ''); // left-padd integer m = m.replace(/^\d+/, function(m) { while (m.length < length) { m = "0" + m; } return m; }); // add decimal component if (m.indexOf('#') < 0) { m += "###0"; } // right-padd decimal m = m.replace(/#(\d+)$/, function(tmp, m) { while (m.length < length) { m += "0"; } return m; }); //console.log(m); return m; }); } list = s.split('|'); list.sort(function(a, b) { var an = padNumbers(a.toLowerCase()), bn = padNumbers(b.toLowerCase()); return an > bn ? 1 : -1; }); heading = document.createElement('h1'); heading.innerHTML = 'Sorting with number formatter'; document.body.appendChild(heading); pre = document.createElement('pre'); pre.innerHTML = list.join("\n"); document.body.appendChild(pre);
body { padding: 20px; } h1 { margin: 10px 0 5px 0; font-weight: bold; }