user3053603
user3053603

Reputation: 1

JavaScript for Prompt input and output sort to alphabetical order

I am trying to create a prompt box for the user to enter data, but the output should display the words in alphabetical order.

Input: A line of text, using prompt.
Output: The words of the input text, in alphabetical order.

I have tried the following but doesn't seem to work for me:

var textArr = prompt("Enter a line of text: ");
var textArr=string.split();
textArr.sort();

alert(textArr.toString(', '));

Upvotes: 0

Views: 7075

Answers (5)

Byte Bit
Byte Bit

Reputation: 513

You have to specify a separator to the split function, otherwise, it will return an array with only one item (the entire string).

Also, if you want to transform an array into a string, you should use the join(glue) function, where glue is the 'connector' of the array's items. If the glue is ommited, the elements will be separated by a comma.

Try this:

var textArr = prompt("Enter a line of text: ");
var textArr = textArr.split(' '); //Separates words by spaces
textArr.sort();


alert(textArr.join(', '));

Upvotes: 0

David Thomas
David Thomas

Reputation: 253396

I'd suggest:

// 1. gets the text from the user,
// 2. splits that string, on white-space(s), into an array of words
// 3. sorts that array lexicographically (the default),
// 4. joins the array back together with the ', ' string
var textArr = prompt("Enter a line of text: ").split(/\s+/).sort().join(', ');

alert(textArr);

JS Fiddle demo.

References:

Upvotes: 3

Tie Zhong
Tie Zhong

Reputation: 19

You have couple issues here:

  1. string is never defined
  2. split delimitor should not be blank (" " instead)
  3. Array.toString() doesn't covert correctly

Try this:

<script language="JavaScript" type="text/javascript">
    var string = prompt("Enter a line of text: ");
    var textArr=string.split(" ");
    textArr.sort();
    alert(textArr.join(', '));
</script>

Upvotes: 0

You didn't specify what is word and how are they separated, so I assumed it's some practice task:

var textArr = prompt("Enter a line of text: ");
alert(textArr.match(/\w+/gi).sort().join());

match(/\w+/gi) matches regular expression /\w+/, which means any latin alphabet character followed or number followed by latin alphabet character followed or number.

Obviously, it won't work with, say, words written in cyrillic or greek, because this will complicate the problem.

Upvotes: 0

bagonyi
bagonyi

Reputation: 3328

You must provide a character that you want to perform the split at:

var input = prompt("Enter a line of text: ");
var textArr = input.split(' ');
console.log(textArr.sort());

Upvotes: 1

Related Questions