w3resource

JavaScript Sorting Algorithm: Alphabetically sorts the characters in a string

JavaScript Sorting Algorithm: Exercise-19 with Solution

Write a JavaScript program to sort the characters in a string alphabetically.

  • Use the spread operator (...), Array.prototype.sort() and String.prototype.localeCompare() to sort the characters in str.
  • Recombine using String.prototype.join('').

Sample Solution:

JavaScript Code:

const sortCharactersInString = str =>
  [...str].sort((a, b) => a.localeCompare(b)).join('');
 
console.log(sortCharactersInString('cabbage'));

Sample Output:

aabbceg

Flowchart:

JavaScript Searching and Sorting Algorithm Exercises: Alphabetically sorts the characters in a string.

Live Demo:

See the Pen javascript-common-editor by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to sort an array of objects, ordered by a property, based on the array of orders provided.
Next: Write a JavaScript program to find the lowest index at which a value should be inserted into an array in order to maintain its sorting order, based on the provided iterator function.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.