I'm tying to solve how to reverse a string. I already figured out how to reverse an array so i'm trying to use that answer in this one. I figure I can convert the string to an array an then just go from there...Well this is what I have so far and tips or advice is welcome.
function reverse(string){
var x = string.split(' ');
for(i=0; i=x.length; i++){
var y= x.pop();
console.log(y);
}
}
See the fiddle : https://jsfiddle.net/1wknqn2d/1/
function reverse(string){
return string.split('').reverse().join('');
}
try this
function reverse(string){
var y =[];
var x = string.split('');
for(i=x.length-1; i>=0; i--){
y.push(x[i]);
}
console.log(y.join(''));
}
or simply
string.split('').reverse().join('');
Aside from the straightforward answer that Ash gave you, you can try an alternative if the reverse()
method is not made available to you or you are not allowed to use it.
- You can create an empty string called
reversed
.
- To iterate through the
string
that was provided and for each character
in that string
, you are going to take that character
and add it to the start of reversed
- Then you are going to return the variable
reversed
.
So you are taking each character
out of the original string and sticking into the new one, one by one.
function reverse(string) {
let reversed = '';
}
So I have declared a temporary variable called reversed
and assigned it an empty string. This is the temporary variable I have assembled over time as I iterate through the string
variable.
Now I need a for
loop, but instead of a classic for
loop I am going to use the ES2015 for...of
loop.
function reverse(string) {
let reversed = '';
for (let character of string) {
}
}
Notice the use of the let
variable identifier? Its because I am going to reassign reversed
like so:
function reverse(string) {
let reversed = '';
for (let character of string) {
reversed = character + reversed;
}
}
Lastly, as outlined in step 3, I return the new assignment of reversed
.
function reverse(string) {
let reversed = '';
for (let character of string) {
reversed = character + reversed;
}
return reversed;
}
So I am taking a temporary variable that is redeclared every single time through this loop of character
. Then I say of
and the iterable object that I want to iterate through, in this case, all the characters of the string
.
So I will iterate through each character
, one by one and then set each character
equal to temporary variable of character
and then I take that character
and add it on to the start of string
reversed
and after the entire loop I return
the string
reversed
.
You can use this in place of the classic for loop just keep in mind you will not be able to use this syntax if you are required to iterate through every third element. In such a case, you have to use the classic for
loop.