javascript排序与字符串无法正常工作

时间:2016-09-10 20:49:41

标签: javascript sorting

我使用JavaScript代码从页面元素输入中对字符串进行排序,它是这样的:

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

输入字符串有逗号和空格,因此如果输入类似于:

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

输出是:

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

你可以注意到它应该在你之前,所以什么错了????

2 个答案:

答案 0 :(得分:1)

你需要用空格分割。

input = input.split(', ');

否则你在字符串的开头有一个空格。

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; }

答案 1 :(得分:1)

您应该在排序前删除空格:

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);