// Notice the surrounding and irregular spacing:
var sentence = " I learn JavaScript and it's fun! ";
sentence = sentence.replace( /^\s+|\s+$/g, " " ); // Trimmed!
Note: replace() takes a regular expression argument; the "\s" pattern stands for "whitespace".
sentence = sentence.replace( /\s+/g, " " );
var words = sentence.split(" "); // Declare array of words
words = words.reverse();
alert( words ); // Test ->
sentence = words.join(" "); // Concatenate array elements into string
var sentence = " I learn JavaScript and it's fun! ";
sentence = sentence.replace( /^\s+|\s+$/g, " " ); // Trim
sentence = sentence.replace( /\s+/g, " " ); // Consolidate
var words = sentence.split(" "); // To array
words = words.reverse(); // Invert word order
sentence = words.join(" "); // Store reversed into sentence
alert( sentence ); // Test final result! Click to run ->