Reverse a String challenge

Reverse a String challenge
0.0 0

#1

Not even sure where to start off here, having severe coder’s block!

Do you first str.split()? Then str.reverse()?


#2
function reverseString(string) {
   string = "hello";
  var array = [" "];
  var newArray = [" "];
  newArray.reverse().join();
  return string;
}

reverseString("hello");

This is what I’ve hashed out so far, though it’s not working. I figured it was better to try and code myself first.


#3

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

You’ll want to convert your string to an array first. A way to do so is

var stringArr = string.split("");

Now you have an array of the characters that make up the string.

Also, if you used .join() without any string between the parentheses, it’ll assume you want to join using commas (so you’ll probably get something like "a,b,c" instead of "abc").


#4

Instead of doing:

var array = [" "];
var newArray = [" "];

try using the split method:

string.split('')

Then try calling the reverse etc on that!

Bonus trick: .split() returns itself, so you can chain the next methods on it.
Bonus trick two. Instead of calling the methods on string and then returning string, try returning string with the methods ex:

function blahblah(string) { return string.method1().method2() }

#5

There are a lot of ways to go about this.
Everything mentioned above is pretty much correct.

function stringReverse(str) {
     return str.split("").reverse().join("");
}

stringReverse("Reverse me");

#6

Hi.

In order to reverse a string, you have to change the order of the characters in string.

The issue is, strings in JavaScript cannot be changed.They’re immutable.You can’t reverse them.

But on the other hand, you can reverse an array.And an array of characters is able to represent a string.

One way to solve this is creating an array of characters like ["h", "o", "u", "s", "e"] (upon which you will be able to do your mutations, like reversing, and finally convert this array back to a new string).

the method split(), when called on a string, just does that.

var array = "house".split(""); // returns a newly created array [ 'h', 'o', 'u', 's', 'e' ]

The double quotes in split("") is a separator.If instead you call "house".split("u") it would return [ 'ho', 'se' ] .
Since we used an empty string "", each character is separated.

now that we have an array, we can call reverse() on it.

array.reverse() // [ 'e', 's', 'u', 'o', 'h' ]

and finally we have to return a string, not an array.Using join(), we can create a new string, based on an existing array.

array.join("") // 'esuoh'

If you need additional reading on the topic : https://medium.freecodecamp.com/how-to-reverse-a-string-in-javascript-in-3-different-ways-75e4763c68cb


#7

You have some typo around this part:


#8

Thank you, I’ve edited my post.