I want to make a string in alphabet order using javascript.
example, if string is "bobby bca" then it must be "abbbbcoy" but I want it in a function - take not that I dont want spaces to be there just alphabet order.
I'm new to javascript here is what I have already:
function make Alphabet(str) {
var arr = str.split(''),
alpha = arr.sort();
return alpha.join('');
}
console.log(Alphabet("dryhczwa test hello"));
4 Answers 4
There are a few things wrong with this code as the comments under your post mentioned.
- the function name is incorrect, it has to be one word as well as the same as when you calling it to actually use the function.
once that is out the way then your code is correct and actually makes things alphabetical
About the spaces you want removed then you can use regex inside the function to remove the spaces and make it output just the characters in alphabetical order like this:
function makeAlphabet(str) {
var arr = str.split(''),
alpha = arr.sort().join('').replace(/\s+/g, '');
return alpha;
}
console.log(makeAlphabet("dryhczwa test hello"));
Other than that this is what I could make of your question
This is updated based on the comment and here is the fiddle: https://jsfiddle.net/ToreanJoel/s2j68s4s/
1 Comment
you start from a string like
var str ='dryhczwa test hello';
create an array from this
var arr = str.split(' ');
then you sort it (alphabetically)
var array = arr.sort();
and you join it back together
var str2 = array.join(' ');
Your function name cannot have spaces;
function makeAlphabet(str) {
return str.split('').sort().join('');
}
Plus, this won't remove spaces, so your example
console.log(makeAlphabet("dryhczwa test hello"));
Will return ' acdeehhllorsttwyz'.
Comments
The function:
function makeAlphabet(str) {
var arr = str.split('');
arr.sort();
return arr.join('').trim();
}
An example call:
console.log(makeAlphabet("dryhczwa test hello"));
// returns "acdeehhllorsttwyz"
Explanation:
Line 1 of makeAlphabet converts the string into an array, with each character beeing one array element.
Line 2 sorts the array in alphabetic order.
Line 3 converted the array elements back to a string and thereby removes all whitespace characters.
function make Alphabet)? And also, you want to remove all spaces?make Alphabet()must bemakeAlphabet()