2016-09-10 2 views
0

I JavaScript-Code verwendet, um eine Zeichenfolge von Seitenelementen Eingabe zu sortieren, und es ist so etwas wie diese:Javascript Arbeits Art nicht richtig mit String

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

die Eingabezeichenfolge hat Komma und Leerräume, so dass, wenn der Eingang so etwas wie:

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 

der Ausgang ist:

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 

und Sie können th bemerken sollte doch vor dir sein, also was ist los ????

+0

einfach wunderbar, warum die Abstimmung nach unten ?????????? ?? –

Antwort

1

sollten Sie Whitespaces entfernen vor dem Sortieren:

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

danke es hat funktioniert, aber was bedeutet "/ \ s +/g" ?? –

+0

Es ist eine Regex, die Leerzeichen in Zeichenfolge ersetzt, Sie können es bei Google finden. – skobaljic

1

Sie müssen mit dem Raum teilen.

input = input.split(', '); 

Andernfalls haben Sie ein Leerzeichen am Anfang der Zeichenfolge.

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

Verwandte Themen