在JavaScript中反转字符串 [英] Reversing a string in JavaScript

查看:139
本文介绍了在JavaScript中反转字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试反转输入字符串

I'm trying to reverse an input string

var oneway = $('#inputfield').val();
var backway = oneway.reverse();

但是firebug告诉我 oneway.reverse()不是一个功能。有什么想法?

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

谢谢

推荐答案

reverse()是一个数组实例的方法。它不会直接用于字符串。您应该首先将字符串的字符拆分为数组,反转数组然后再连接回字符串:

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("");

更新

上述方法仅对常规字符串安全。请参阅以下Mathias Bynens的评论,并他的回答以获得安全的反向方法。

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.

这篇关于在JavaScript中反转字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆