JavaScript Code


How to sort characters in string in ascending order in JavaScript?


Sort characters in a string in ascending order

Given a string, arrange the characters of the given string in ascending order, using JavaScript.

Solution

To arrange the characters of a given string in ascending order using JavaScript, first split the string into character array, sort the array in ascending order, and join the array.

String.split("") splits the string into array of characters. Observe that we passed an empty string as argument to split() method.

Array.sort() sorts the array of characters in ascending order.

Array.join("") joins the array of characters into a string. Again, observe that we have passed an empty string to join() method. Empty string is used as delimiter between the items of the array while joining.

All these methods can be joining together via chaining mechanism. The string str can be reversed using the following expression.

str.split("").sort().join("")

Program

1. Given a string in str. Reverse the string str .

let str = 'hello world';
let output = str.split("").sort().join("");
console.log(output);