Write a javascript function to sort the lines of a string in alphabetical order.
- User
Write a javascript function to sort the lines of a string in alphabetical order.
- Assistant
Certainly! Below is a JavaScript function that takes a string as input, where each line is separated by a newline character (
\n). It will split the string into lines, sort the lines alphabetically, and then join them back together into a single string with sorted lines.function sortLinesAlphabetically(inputString) { // Split the input string by newline character into an array of lines const lines = inputString.split('\n'); // Sort the array of lines alphabetically lines.sort((a, b) => a.localeCompare(b)); // Join the sorted lines back into a single string with newline characters const sortedString = lines.join('\n'); return sortedString; } // Example usage: const text = `banana apple cherry`; const sortedText = sortLinesAlphabetically(text); console.log(sortedText);
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.