In JavaScript, use the sort() method to sort letters: by default, sorted according to ASCII code value (lowercase letters first). By providing a custom comparison function, it is possible to sort according to custom rules (for example: case-insensitive).
How to sort letters in JavaScript
Answer: Use sort ()
method, which can sort letters in a string based on ASCII code values or custom comparison functions.
Detailed description:
To sort letters in a JavaScript string, you can use the sort()
method. This method converts the string to an array and sorts its elements according to the specified collation.
Use ASCII code value to sort:
sort()
method will sort letters according to ASCII code value . Lowercase letters have a smaller ASCII code value than uppercase letters, so lowercase letters will be sorted before uppercase letters. <code class="javascript">const str = "hello"; const sortedStr = str.split("").sort(); console.log(sortedStr); // ["e", "h", "l", "l", "o"]</code>
Use custom comparison function to sort:
You can also provide a custom comparison function to control the sorting rules. The comparison function accepts two elements as arguments and returns a number:
<code class="javascript">const compareFunction = (a, b) => { const lowerA = a.toLowerCase(); const lowerB = b.toLowerCase(); if (lowerA < lowerB) { return -1; } else if (lowerA > lowerB) { return 1; } else { return 0; } }; const str = "Hello"; const sortedStr = str.split("").sort(compareFunction); console.log(sortedStr); // ["e", "H", "l", "l", "o"]</code>
The above is the detailed content of How to sort input letters in js. For more information, please follow other related articles on the PHP Chinese website!