0

I am working on the project of reversing a string and am getting commas in between each character in the reversed string.

`var testString = prompt("Enter a 'string'");

document.getElementById("demo").innerHTML = testString;

var reverse = function(string){
    var gnirts = [];
    for (i = 0; i < string.length; i++){
        gnirts.unshift(string[i]);
    };
    gnirts.toString();
    document.getElementById("revString").innerHTML = gnirts;
};

reverse(testString);`

I entered "Honky Toast" in the prompt and "t,s,a,o,T, ,y,k,n,o,H" was returned. Why am I getting the ","s and how do I avoid them?

BigBadBigBad
  • 421
  • 5
  • 9
  • because it's an array? – stackoverfloweth Jul 09 '15 at 18:26
  • 1
    try this gnirts.join(''); – stackoverfloweth Jul 09 '15 at 18:27
  • 1
    possible duplicate of [How do you reverse a string in place in JavaScript?](http://stackoverflow.com/questions/958908/how-do-you-reverse-a-string-in-place-in-javascript) – Al.G. Jul 09 '15 at 18:30
  • I think your problem is not `why do I get commas`, it is `how to reverse a string`. You didn't say you didn't want to use built-in functions like `Array.reverse()`, so the question above should solve your problem. – Al.G. Jul 09 '15 at 18:32
  • gnirts.join(' '); gives me "t s a o T y k n o H" when what I would like is "tsaoT yknoH" AH! My bad, I had a space inside the ''. – BigBadBigBad Jul 09 '15 at 18:53
  • I know there are lots of ways to reverse a string. I am more interested in learning about what is going on and how to fix this specific issue, rather than to simply reverse the string without actually learning any more. – BigBadBigBad Jul 09 '15 at 18:53

2 Answers2

2

Use join, and pass an empty string as separator.

REPL:

x = [1,2,3,4,5]
[ 1, 2, 3, 4, 5 ]

x.join()
'1,2,3,4,5'

x.join('')
'12345'
7zark7
  • 10,015
  • 5
  • 39
  • 54
2

Instead of calling gnirts.toString(); You should use join. Array's implementation of toString separates each item with a comma.

var reverse = function(string){
    var gnirts = [];
    for (i = 0; i < string.length; i++){
        gnirts.unshift(string[i]);
    };
    document.getElementById("revString").innerHTML = gnirts.join('');
};
  • This did it. When/why would one want an array to a string separated by commas? – BigBadBigBad Jul 09 '15 at 18:56
  • Display purposes. If I had an array of numbers `[1, 2, 3, 4]` and I printed it, I wouldn't normally want it to print as `1234`. If it did, I couldn't discern whether it was originally `[1, 2, 3, 4]` or `[12, 34]`, or any other combination of those four digits. – Nicholas Thomson Jul 09 '15 at 19:58