Make sure you specify an empty string to .join, otherwise you'll get commas between each character:
Copy"McDonalds".split("").reverse().join(""); // "sdlanoDcM"
Answer from p.s.w.g on Stack OverflowThis is because .reverse() is used on the output of .split("").
Using .reverse() by itself doesn't work because the line before it doesn't directly change it unless you reassign it with stringArg = stringArg.split("");. The first line would return the array of characters but doesn't change stringArg directly.
So:
stringArg.split("").reverse().join("");
means to join all elements within the array whose elements are in reverse order based on the spliting of the string. In other words, .reverse() is used on stringArg.split(""), not just stringArg and same with .join(""): it is applied to stringArg.split("").reverse() not just stringArg.
Thus the solution would be:
function revString2 (stringArg) {
a = stringArg.split("");
b = a.reverse();
c = b.join("");
return c;
}
The first example chains the results of previous method call, where .split() returns an array as first link in chain.
The second example performs a separate task on the original string at each line, not chained to the first line which returns an array.
.reverse() is not a method defined at String.prototype, resulting in the error at stringArg.reverse() at second line of function call.