Reputation: 1
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
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
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);
References:
Upvotes: 3
Reputation: 19
You have couple issues here:
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
Reputation: 12146
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
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