Reversing a string in JavaScript

后端 未结 15 2049
野的像风
野的像风 2020-11-28 03:58

I\'m trying to reverse an input string

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

but f

15条回答
  •  孤街浪徒
    2020-11-28 04:28

    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.

提交回复
热议问题