This is the third post in a series of at least 10 code challenges. You can find the others here.
Compared to the previous two challenges, today’s challenge was short and straightforward.
Challenge: Given a string, the function reverseString should return the same string backwards. For example, reverseString(“This string”) would return “gnirts siht.” When writing your function, assume the message contains only letters and spaces, and all words are separated by one space.
Here’s my solution collapsed:
[code language=”javascript” collapse=”true”]
<script>
var reverseString = function(string) {
// Split the string into individual characters
var characters = string.split("");
// Create a variable for the string we want to return
var reversedString = "";
// Loop over the characters backwards and add them to the new string
for (var i=(characters.length-1); i>=0; i–) {
reversedString += characters[i];
}
// Write out the reversedString to the page
document.write(reversedString);
};
reverseMessage("edoc terces eht si sihT");
</script>
[/code]
To start, I used the split method to break apart the original string. If you pass in an empty string to the method, it breaks up the string into characters rather than individual words. Now, I had all of the individual characters stored in an array and assigned to the variable characters
. I created a new variable to hold the reversed string (reversedString
). Then, I looped over the characters array with a for loop. By setting i equal to (characters.length-1), I could start at the end of the array. Finally, using the += operator, I added the items to the new array and wrote that new array to the page.