user2070685
user2070685

Reputation: 79

How can I alphabetize within a <textarea>? JavaScript sort()?

I've seen a few sites now that alphabetize what ever you put in their textarea I was wondering what I would have to do in order to add a button to mine that would produce that? I'm guessing the "JavaScript sort()" function, but I really don't know. All I've seen with that so far is using it to alphabetize arrays. This would be for anything entered, per line, in an open textarea. Any ideas?

Thanks for taking the time to read this.

Upvotes: 5

Views: 1932

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 219936

split the string into an array, sort it, then join it back together:

var textarea = document.getElementById("theTextareaId"); // or whatever...
textarea.value = textarea.value.split("\n").sort().join("\n");

Upvotes: 13

Related Questions