根据子字符串中的数字对字符串进行排序

时间:2016-08-10 16:50:04

标签: javascript

我有一个这样的字符串" is2 Thi1s T4est 3a",我需要对它进行排序,所以 数组看起来像这样" Thi1s是2 3a T4est"。 Number可以出现在字符串中的任何位置。我知道如何按字母顺序排序字符串以及如何对数字数组进行排序,但在这种情况下如何完成?有没有一种方法可以帮助它在数字上忽略字母? 我一直试图完成这项任务,任何帮助都将不胜感激!

2 个答案:

答案 0 :(得分:9)

您可以根据存储在每个字符串中的数值来分隔空格和sort

let words = "is2 Thi1s T4est 3a".split(' ');
words.sort((a, b) => a.replace(/[^\d]+/g, '') - b.replace(/[^\d]+/g, ''));
console.log(words.join(' '));

答案 1 :(得分:2)

首先定义一个比较函数。

foreach -parallel ($server in $targetServers)
{
    InlineScript
        {
            $serverName = $using:server.serverName;
            $serverDrive = $using:server.drive;
            $bakFileName = $using:testBakFileName;
            $targetFileFullPath = "\\$servername\$serverDrive\$bakFileName";
            $sqlScript = 
                "ALTER DATABASE $using:TargetDbName SET Single_User WITH Rollback Immediate
                GO
                RESTORE DATABASE $using:TargetDbName FROM DISK = N'$targetFileFullPath' WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 10
                ALTER DATABASE $using:TargetDbName SET MULTI_USER"
            Write-Output "  Restoring $using:TargetDbName from $targetFileFullPath on $serverName with $sqlScript"
            Invoke-Sqlcmd -Query "$sqlScript" -Verbose -queryTimeout 65534
        }
     }

然后使用它。

compare = function(x, y) {
  return x.match(/\d+/g)[0] - y.match(/\d+/g)[0];
}

或者如果你喜欢一行,

var z = "is2 Thi1s T4est 3a";
z.split(" ").sort(compare).join(" ");
//"Thi1s is2 3a T4est"