Open In App

How to returns a passed string with letters in alphabetical order in JavaScript ?

Last Updated : 09 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Let’s say we need to convert the string into alphabetical order.

For example:

geeksforgeeks -> eeeefggkkorss

Approach: The task is to create a function that takes a string and returns the alphabetical order of that string.

Hence to achieve this we will go under the split, sort, and join method in javascript.

  • Step 1: Split the given string into characters with the help of the split() method in javascript and store that in an array
  • Step 2: Sort the array of characters in alphabetical order with the help of sort() function
  • Step 3: Join the characters into one string with the help of join() method

Example:

Javascript




<script>
  function alpha(str) {
    var arr = str.split(""); // splits the string
    res = arr.sort().join(""); // sort the array and joins to form a string
    return res; // returns the result
  }
  console.log("taking geeksforgeeks as a string");
  console.log(alpha("geeksforgeeks"));
</script>


Output:

taking geeksforgeeks as a string
eeeefggkkorss

Exceptional case: If we try to put whitespace in between our passing string it will result in putting that white space in starting of the resultant string. Like in the above example string has 1 white space and in the resultant string it is useless, so to get rid of that we can use white space regular expression i.e. \s+ for selecting white spaces and replacing it with an empty string.

Example:

Javascript




<script>
  function alpha(str) {
    var arr = str.split("");
    res = arr.sort().join("");
    rws = res.replace(/\s+/g, "");
    return rws;
  }
 
  console.log("taking geeksforgeeks portal as a string");
  console.log(alpha("geeksforgeeks portal"));
</script>


Output:

taking geeksforgeeks portal as a string
aeeeefggkklooprrsst


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads