how to sort strings in javascript numerically

前端 未结 7 1480
一个人的身影
一个人的身影 2021-02-14 12:48

I would like to sort an array of strings (in javascript) such that groups of digits within the strings are compared as integers not strings. I am not worried about signed or fl

7条回答
  •  南方客
    南方客 (楼主)
    2021-02-14 13:20

    I needed a way to take a mixed string and create a string that could be sorted elsewhere, so that numbers sorted numerically and letters alphabetically. Based on answers above I created the following, which pads out all numbers in a way I can understand, wherever they appear in the string.

    function padAllNumbers(strIn) {
        // Used to create mixed strings that sort numerically as well as non-numerically
        var patternDigits = /(\d+)/g; // This recognises digit/non-digit boundaries
        var astrIn = strIn.split( patternDigits ); // we create an array of alternating digit/non-digit groups
    
        var result = "";
    
        for (var i=0;i

提交回复
热议问题