开发者

Reversing a string in JavaScript

开发者 https://www.devze.com 2022-12-09 19:12 出处:网络
I\'m trying to reverse an input string var oneway = document.getElementById(\'input_fiel开发者_如何学Cd\').value();

I'm trying to reverse an input string

var oneway = document.getElementById('input_fiel开发者_如何学Cd').value();
var backway = oneway.reverse();

but firebug is telling me that oneway.reverse() is not a function. Any ideas?

Thank you


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.


The following technique (or similar) is commonly used to reverse a string in JavaScript:

// Don’t use this!
var naiveReverse = function(string) {
    return string.split('').reverse().join('');
}

In fact, all the answers posted so far are a variation of this pattern. However, there are some problems with this solution. For example:

naiveReverse('foo 
0

精彩评论

暂无评论...
验证码 换一张
取 消