Thursday, October 23, 2025
HomeLanguagesJavascriptSort a string alphabetically using a function in JavaScript

Sort a string alphabetically using a function in JavaScript

Sort a string alphabetically by creating a user-defined function to perform sorting. This function is useful when we receive a random set of characters as a string and we want it to be sorted in an alphabetical manner. To perform this task we will use multiple inbuilt methods and combine them to create a helper function.

Approach 1: Using split() method, sort() method and join() method

Note: We will use the concept of method chaining to reduce the lines of code.

Example: In this example, we will implement the above approach.

Javascript




function sortAlpha(word) {
    return word.split("")
               .sort()
               .join("");
}
 
let randomWord = "sdfjwefic";
console.log(sortAlpha(randomWord))


Output:

cdeffijsw

Approach 2: Using spread operator, sort() method and localeCompare()

Example: We will use the method chaining and arrow function syntax to make the code short and readable.

Javascript




function sortAlpha(word) {
    return [...word].sort((a,b)=>a.localeCompare(b)).join("")
}
 
let randomWord = "sdFjwefiC";
console.log(sortAlpha(randomWord));


Output:

CdefFijsw

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS