javascriptstring

Reversing a string in JavaScript


I'm trying to reverse an input string:

var oneway = document.getElementById('input_field').value();
var backway = oneway.reverse();

But Firebug is telling me that oneway.reverse() is not a function. Any ideas?


Solution

  • reverse() is a method of array instances. It won't directly work on a string. You should first split the characters of the string into an array, reverse the array and then join back into a string:

    var backway = oneway.split("").reverse().join("");
    

    Update

    The method above is only safe for "regular" strings. Please see comment by Mathias Bynens below and also his answer for a safe reverse method.