Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 26 Apr, 2021

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 snd 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:

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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :