Skip to content

Instantly share code, notes, and snippets.

@petergi
Last active December 28, 2023 05:46
Show Gist options
  • Save petergi/1564345a29decf1ae967827446f92267 to your computer and use it in GitHub Desktop.
Save petergi/1564345a29decf1ae967827446f92267 to your computer and use it in GitHub Desktop.
Alphabetically sorts the characters in a string.
// - Use the `split()` method to convert the string `str` into an array of characters.
// - Use the `sort()` method with a compare function to sort the characters in the array.
// - Use the `join()` method to recombine the sorted characters into a string.
/**
* Sorts the characters in a string in ascending order.
*
* @param {string} str - The string to sort.
* @return {string} The sorted string.
*/
function sortCharactersInString(str) {
return str
.split("")
.sort((a, b) => a.localeCompare(b))
.join("")
}
sortCharactersInString("cabbage") //= 'aabbceg'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment