How to returns a passed string with letters in alphabetical order in JavaScript ?
Let’s say we need to convert the string into alphabetical order.
For example:
w3wiki -> eeeefggkkorss
Approach: The task is to create a function that takes a string and returns the alphabetical order of that string.
- 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 w3wiki as a string" ); console.log(alpha( "w3wiki" )); </script> |
Output:
taking w3wiki 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 w3wiki portal as a string" ); console.log(alpha( "w3wiki portal" )); </script> |
Output:
taking w3wiki portal as a string aeeeefggkklooprrsst
Contact Us