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"
<script>
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);
</script>
I am able to make it using the inbuilt methods. But the question asks to use only use
So how would I go about this?
ok, so you are allowed to use charAt which you can use to find the spaces between words. When you know where the spaces are you can use substring to isolate the individual words and store them in variables. Then you can move them around and join them back together. So as an example:
var string = "Hello World",
words = [],
reversedString="",
i;
for (i=0; i<string.length; i++) {
if (string.charAt(i) === " ") {
words.push(string.substring(0, i));
words.push(string.substring(i));
}
}
for (i=words.length-1; i>=0; i--) {
reversedString += words[i];
}
Please note this is just a simple (untested) example and will only work for a string of two words. If you want to make it work with more you need to change the logic around the substrings. Hope it helps!
EDIT: Just noticed I didn't reverse the string at the end, code updated.
Here's a couple of references in case you need them: substring charAt