Without using the split reverse and join functions, how would one do such a thing?
The Problem Given: Reverse the words in a string Sample Input: "Hello World" Sample Output: "World Hello"
var newString = "";
var theString = prompt["Enter a Phrase that you would like to reverse [Ex. Hello world]"];
newString = theString.split[" "].reverse[].join[" "]
document.write[newString];
asked Nov 23, 2015 at 17:43
lazerrougelazerrouge
892 silver badges8 bronze badges
4
Arrays can be used like stacks out of the box. And stacks are LIFO, which is what you need.
function reverseWords[str] {
var word, words, reverse;
words = str.match[/[?:\w+]/g];
reverse = '';
while[word = words.pop[]] {
reverse += word + ' ';
}
return reverse.trim[];
}
reverseWords['hello world'];
Or use the call stack as your stack:
function reverseWords[str] {
var result = '';
[function readWord[i = 0] {
var word = '';
if[i > str.length] {
return '';
}
while[str[i] !== ' ' && i < str.length] {
word += str[i];
i++;
}
readWord[++i]; // Skip over delimiter.
result += word + ' ';
}[]];
return result.trim[];
}
reverseWords['hello world'];
answered Nov 23, 2015 at 18:56
Ben AstonBen Aston
50.5k61 gold badges194 silver badges324 bronze badges
Another idea for reversing the words in a String is using a Stack data structure. Like so:
var newString = "";
var theString = prompt["Enter a Phrase that you would like to reverse [Ex. Hello world]"];
var word = "";
var c;
var stack = [];
for [var i = 0, len = theString.length; i < len; i++] {
c = theString[i];
word += c;
if [c == " " || i == [len-1]] {
word = word.trim[];
stack.push[word];
word = "";
}
}
while [s = stack.pop[]] {
newString += s + " ";
}
console.log[newString];
answered Nov 23, 2015 at 18:31
Lucas PotterskyLucas Pottersky
1,7145 gold badges21 silver badges37 bronze badges
You could also go fancy and try something like this:
I couldn't come up with a shorter solution.
var newString = "";
var theString = prompt["Enter a Phrase that you would like to reverse [Ex. Hello world]"];
theString.replace[/[^\s]*/g, function [value] {
newString = value + ' ' + newString;
}];
document.write[newString];
answered Nov 23, 2015 at 18:27
Of the millions of different solutions, the least amount of typing I could come up with involves using lastIndexOf
and substring
.
var str = "The quick brown fox",
reversed = "",
idx;
while[true] {
idx = str.lastIndexOf[" "]
reversed = reversed + str.substring[idx].trim[] + " "
if [idx < 0] break;
str = str.substring[0, idx]
}
reversed.trim[] # Oh, yes, trim too
Output:
"fox brown quick The"
answered Nov 23, 2015 at 18:26
klironkliron
4,1854 gold badges29 silver badges47 bronze badges
The simplest way to do in javascript. Here replace[] have /,/g it will replace all comma from the string to space.
var msg = 'Hello world I am Programmer';
var newstr = msg.split[" "].reverse[].join[].replace[/,/g, ' '];
console.log[newstr]
;
answered Apr 24, 2019 at 5:43