Aghyad Algllad
Aghyad Algllad

Reputation: 1805

javascript sort not working correctly with string

I used JavaScript code to sort a string from page elements input, and it's something like this:

a=document.getElementsByTagName("textarea");
input=a[0].innerHTML;
input=input.split(',');
input=input.sort();
alert(input);
var str=input.join();
str=str.replace(" ","");

the input string has comma and white spaces ,so if the input is something like:

yet, must, has, wants, would, some, are, let, own, can, could, which, his, had, got, our, only, also, every, after, other, may, you, them, while, ever, what, get, its, why, their, her, him, just, say, this, than, have, able, least, like, whom, nor, cannot, into, among

the output is :

able, after, also, among, are, can, cannot, could, ever, every, get, got, had, has, have, her, him, his, into, its, just, least, let, like, may, must, nor, only, other, our, own, say, some, than, their, them, this, wants, what, which, while, whom, why, would, you,yet

and you can notice that yet should be before you,so whats wrong????

Upvotes: 0

Views: 1478

Answers (2)

skobaljic
skobaljic

Reputation: 9634

You should remove white spaces before sorting:

var input = 'yet, must, has, wants, would, some, are, let, own, can, could, which, his, had, got, our, only, also, every, after, other, may, you, them, while, ever, what, get, its, why, their, her, him, just, say, this, than, have, able, least, like, whom, nor, cannot, into, among';
input = input.replace(/\s+/g, '').split(',').sort();
console.log(input);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386570

You need to split with space.

input = input.split(', ');

Otherwise you have a space at the beginning of the string.

var input = 'yet, must, has, wants, would, some, are, let, own, can, could, which, his, had, got, our, only, also, every, after, other, may, you, them, while, ever, what, get, its, why, their, her, him, just, say, this, than, have, able, least, like, whom, nor, cannot, into, among';
console.log(input.split(', ').sort());
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions