2016-09-10 5 views
0

Я использовал код JavaScript, чтобы отсортировать строки из входных страниц элементов, и это что-то вроде этого: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 

и вы можете заметить тыс пока еще должно быть до вас, так что не так ????

+0

просто замечательно, почему голосование вниз ?????????? ?? –

ответ

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

+0

спасибо, что это сработало, но что означает «/ \ s +/g»? –

+0

Это регулярное выражение, которое заменяет пробелы в строке, вы можете найти его в google. – skobaljic

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

Смежные вопросы