10

Having a little trouble understanding what this does. If I have a string,

Using "Mcdonalds" as an example, I do:

"McDonalds".split("").reverse().join();

What exactly am I doing?

Am I splitting each character (M c D o n a l d s), then reversing it (s d l a n o D c M) then joining to get (sdlanoDcM)? (Trying to see if I understand this right)

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • No it's not at all, but thanks for your input. –  Feb 27 '14 at 16:59
  • Read the documentation for each function being called: [split](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split), [reverse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse), [join](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) – Patrick Q Feb 27 '14 at 17:00
  • What you want is to reverse a string, isn't? – ronnyfm Feb 27 '14 at 17:00
  • 1
    @ronnyfm No I was just trying to understand what happens when you use all three at once :D –  Feb 27 '14 at 17:06

2 Answers2

25

Make sure you specify an empty string to .join, otherwise you'll get commas between each character:

"McDonalds".split("").reverse().join(""); // "sdlanoDcM"
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • okay thank you, I thought this is what it was doing, just trying to make sure –  Feb 27 '14 at 16:59
  • if I wanted to take in a string as an argument inside a function, and split it would I just do this then?: var h = "helloworld!"; function splitString(h) { h.split(""); return h; } –  Feb 27 '14 at 17:15
  • @user3308129 Split returns a new array. It doesn't modify the variable, `h`. Try `function splitString(h) { return h.split(""); }`. – p.s.w.g Feb 27 '14 at 18:04
2

If you want sdlanoDcM

then use "" inside .join():

alert("McDonalds".split("").reverse().join(""));
ashbuilds
  • 1,401
  • 16
  • 33