[js] 基于字符串中的数字进行字符串排序
#1
function order(words) { return words.split(' ').sort((a, b) => a.match(/\d/) - b.match(/\d/)).join(' '); }
#2
function order(words) { return words.split(" ").sort((a, b) => a.replace(/[^\d]/g, "") - b.replace(/[^\d]/g, "")).join(" ") }
#3
function order(words) { var reg = /[^\d]+/g, original = words.split(' '), correlation = [], reorder = []; if (words === '') { return words; } original.forEach(function(ele, index) { correlation[index] = {}; correlation[index]['i'] = index; correlation[index]['v'] = Number(ele.replace(reg, '')); }); correlation.sort(function(a, b) { return a.v - b.v; }); correlation.forEach(function(ele, index) { reorder.push(original[ele.i]); }); return reorder.join(' '); }
#test
console.log(order("is2 Thi1s T4est 3a")); console.log(order("4of Fo1r pe6ople g3ood th5e the2")); console.log(order(""));