A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/sort-a-string-in-javascript/ below:

Sort a String in JavaScript

Sort a String in JavaScript

Last Updated : 23 Jul, 2025

Here are the most used methods to sort characters in a string using JavaScript.

Using split(), sort(), and join()

The most simple way to sort a string is to first convert it to an array of characters, sort the array, and then join it back into a string.

JavaScript
let s1 = "javascript";
let s2 = s1.split('').sort().join('');
console.log(s2);

Output

aacijprstv
Using Array.from() with sort()

Similar to split(), you can also use Array.from() to convert the string to an array of characters, then apply sort() and join() to get the sorted result.

JavaScript
let s1 = "javascript";
let s2 = Array.from(s1).sort().join('');
console.log(s2);

Output

aacijprstv
Using a for Loop and Custom Sorting

For custom sorting (e.g., sorting by frequency, case-insensitivity), you can convert the string to an array and use a for loop to implement custom sorting logic.

JavaScript
let s1 = "JavaScript";
let s2 = s1
    .split("")
    .sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }))
    .join("");
console.log(s2);

Output

aaciJprStv
Using reduce() with Sorting Logic

If you need more complex sorting, reduce() can help by building a sorted string as it processes each character, but this approach is less efficient and less commonly used.

JavaScript
let s1 = "javascript";
let s2 = s1
    .split("")
    .reduce((acc, char) => acc + char, "")
    .split("")
    .sort()
    .join("");
console.log(s2);

Output

aacijprstv

The split(), sort(), and join() approach is the most popular and efficient for basic character sorting in a string.

Please refer Sort a String for different algorithms and their complexities to sort a string.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4