Introduction
In this lab, we will explore how to sort characters in a string in alphabetical order using JavaScript. We will use the spread operator, Array.prototype.sort(), and String.prototype.localeCompare() to achieve this. By the end of the lab, you will have a good understanding of how to manipulate strings in JavaScript using these methods.
Here's how to sort characters in a string:
Use the following code to sort the characters in a string alphabetically:
const sortCharactersInString = (str) =>
[...str].sort((a, b) => a.localeCompare(b)).join("");
To start, open the Terminal/SSH and type node to begin practicing coding.
Example usage:
sortCharactersInString("cabbage"); // 'aabbceg'
Summary
Congratulations! You have completed the Sort Characters in String lab. You can practice more labs in LabEx to improve your skills.