JavaScript: Alphabetize a given string
JavaScript String: Exercise-25 with Solution
Write a JavaScript function to alphabetize a given string.
Alphabetize string : An individual string can be alphabetized. This rearranges the letters so they are sorted A to Z.
Test Data:
console.log(alphabetize_string('United States'));
Output:
"SUadeeinsttt"
Visual Presentation:
Sample Solution:
JavaScript Code:
// Function to alphabetize a string
function alphabetize_string(str)
{
// Split the string into an array of characters, sort them alphabetically, then join them back into a string
return str.split('').sort().join('').trim();
}
// Output the result of alphabetizing the string 'United States'
console.log(alphabetize_string('United States'));
Output:
SUadeeinsttt
Explanation:
The above JavaScript code defines a function called "alphabetize_string()" that takes a string ('str') as input and returns the string with its characters sorted alphabetically. Here's a breakdown of what each part does:
- str.split(''): Splits the input string into an array of characters.
- .sort(): Sorts the array of characters alphabetically.
- .join(''): Joins the sorted array back into a string.
- .trim(): Removes any leading or trailing whitespace from the resulting string.
- return: Returns the alphabetized string.
Flowchart:
Live Demo:
See the Pen JavaScript Alphabetize a given string - string-ex-25 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function to truncate a string to a certain number of words.
Next: Write a JavaScript function to remove the first occurrence of a given 'search string' from a string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/javascript-exercises/javascript-string-exercise-25.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics