sort a given string

时间:2023-03-09 14:52:17
sort a given string

my solution:

function order(words){
var splitToArr = words.split(' '),
len = splitToArr.length,
newArr = [],
newWords = "";
if (!len) {
return words;
}
else {
for (var i = 0; i < len; i++) {
var replaceToNum = splitToArr[i].replace(/[^1-9]/ig, '');
newArr[replaceToNum - 1] = splitToArr[i];
}
}
newWords = newArr.join(' ');
return newWords;
} test: order("is2 Th1is tes3t"); 返回("Th1is is2 tes3t");

a simple solution:

function order(words) {

   return words.split(' ').sort(function(a, b) {

    return a.match(/\d/) - b.match(/\d/);

   }).join(' ');

}