How do you reverse a string in place (or in-place) in JavaScript when passed to a function with a return statement? All without using the built-in functions? .reverse()
, .charAt()
, etc.
当使用返回语句传递给函数时,如何在JavaScript内(或就地)将字符串反转?都不使用内置函数?.charAt .reverse()()等。
40 个解决方案
#1
640
As long as you're dealing with simple ASCII characters, and you're happy to use built-in functions, this will work:
只要您处理的是简单的ASCII字符,并且您很乐意使用内置函数,这将会工作:
function reverse(s){
return s.split("").reverse().join("");
}
If you need a solution that supports UTF-16 or other multi-byte characters, be aware that this function will give invalid unicode strings, or valid strings that look funny. You might want to consider this answer instead.
如果您需要一个支持UTF-16或其他多字节字符的解决方案,请注意这个函数将给出无效的unicode字符串,或者看起来很有趣的有效字符串。你可能想要考虑这个答案。
#2
371
The following technique (or similar) is commonly used to reverse a string in JavaScript:
下面的技术(或类似的)通常用于在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 ???? bar');
// → 'rab �� oof'
// Where did the `????` symbol go? Whoops!
If you’re wondering why this happens, read up on JavaScript’s internal character encoding. (TL;DR: ????
is an astral symbol, and JavaScript exposes it as two separate code units.)
如果您想知道为什么会发生这种情况,请阅读JavaScript的内部字符编码。(TL;DR:????是一个星体symbol,和JavaScript units.)暴露了它作为两个单独的代码
But there’s more:
但还有更多:
// To see which symbols are being used here, check:
// http://mothereff.in/js-escapes#1ma%C3%B1ana%20man%CC%83ana
naiveReverse('mañana mañana');
// → 'anãnam anañam'
// Wait, so now the tilde is applied to the `a` instead of the `n`? WAT.
A good string to test string reverse implementations is the following:
测试字符串反向实现的好字符串如下:
'foo ???? bar mañana mañana'
Why? Because it contains an astral symbol (????
) (which are represented by surrogate pairs in JavaScript) and a combining mark (the ñ
in the last mañana
actually consists of two symbols: U+006E LATIN SMALL LETTER N and U+0303 COMBINING TILDE).
为什么?因为它包含了一个星体象征(????)(which由代理对JavaScript)和结合马克(the ñ过去mañana实际上包含两个symbols:U+006E拉丁小写字母N和U+0303结合TILDE).
The order in which surrogate pairs appear cannot be reversed, else the astral symbol won’t show up anymore in the ‘reversed’ string. That’s why you saw those ��
marks in the output for the previous example.
代理对出现的顺序不能反转,否则星体符号将不会再出现在“反转”字符串中。这就是为什么你看到这些��标志前面的示例输出。
Combining marks always get applied to the previous symbol, so you have to treat both the main symbol (U+006E LATIN SMALL LETTER N) as the combining mark (U+0303 COMBINING TILDE) as a whole. Reversing their order will cause the combining mark to be paired with another symbol in the string. That’s why the example output had ã
instead of ñ
.
组合标记总是应用于前面的符号,所以您必须将主符号(U+006E拉丁小字母N)作为组合标记(U+0303组合TILDE)作为一个整体。反转它们的顺序将使组合标记与字符串中的另一个符号配对。这就是为什么示例输出̃代替n。
Hopefully, this explains why all the answers posted so far are wrong.
希望这能解释为什么到目前为止所有的答案都是错误的。
To answer your initial question — how to [properly] reverse a string in JavaScript —, I’ve written a small JavaScript library that is capable of Unicode-aware string reversal. It doesn’t have any of the issues I just mentioned. The library is called Esrever; its code is on GitHub, and it works in pretty much any JavaScript environment. It comes with a shell utility/binary, so you can easily reverse strings from your terminal if you want.
为了回答您的第一个问题——如何[正确地]反转JavaScript中的字符串——我编写了一个小的JavaScript库,它能够反转单点感知的字符串。它没有我刚才提到的任何问题。这个图书馆叫做Esrever;它的代码在GitHub上,几乎可以在任何JavaScript环境中使用。它附带一个shell实用程序/二进制文件,因此如果您愿意,可以很容易地从终端反转字符串。
var input = 'foo ???? bar mañana mañana';
esrever.reverse(input);
// → 'anañam anañam rab ???? oof'
As for the “in-place” part, see the other answers.
至于“就地”部分,请参阅其他答案。
#3
86
String.prototype.reverse=function(){return this.split("").reverse().join("");}
or
或
String.prototype.reverse = function() {
var s = "";
var i = this.length;
while (i>0) {
s += this.substring(i-1,i);
i--;
}
return s;
}
#4
48
The whole "reverse a string in place" is an antiquated interview question C programmers, and people who were interviewed by them (for revenge, maybe?), will ask. Unfortunately, it's the "In Place" part that no longer works because strings in pretty much any managed language (JS, C#, etc) uses immutable strings, thus defeating the whole idea of moving a string without allocating any new memory.
整个“反向字符串到位”是一个过时的面试问题——程序员,以及被他们面试过的人(也许是为了报复?)不幸的是,“到位”部分不再起作用,因为几乎任何托管语言(JS、c#等)中的字符串都使用不可变的字符串,从而挫败了在不分配任何新内存的情况下移动字符串的整个想法。
While the solutions above do indeed reverse a string, they do not do it without allocating more memory, and thus do not satisfy the conditions. You need to have direct access to the string as allocated, and be able to manipulate its original memory location to be able to reverse it in place.
虽然上面的解决方案确实会反转一个字符串,但它们在不分配更多内存的情况下不会这样做,因此不满足条件。您需要直接访问所分配的字符串,并且能够操作其原始内存位置,以便能够在适当的位置上反转它。
Personally, i really hate these kinds of interview questions, but sadly, i'm sure we'll keep seeing them for years to come.
就我个人而言,我真的很讨厌这样的面试问题,但遗憾的是,我相信我们会在未来的几年里一直看到这些问题。
#5
42
Detailed analysis and ten different ways to reverse a string and their performance details.
详细分析和10种不同的方法来反转字符串及其性能细节。
http://eddmann.com/posts/ten-ways-to-reverse-a-string-in-javascript/
http://eddmann.com/posts/ten-ways-to-reverse-a-string-in-javascript/
Perfomance of these implementations:
遵守这些实现:
Best performing implementation(s) per browser
每个浏览器的最佳执行
- Chrome 15 - Implemations 1 and 6
- Chrome 15 -实现1和6。
- Firefox 7 - Implementation 6
- Firefox 7 -实现6。
- IE 9 - Implementation 4
- IE 9 -实现4
- Opera 12 - Implementation 9
- Opera 12 -实现9。
Here are those implementations:
这里是这些实现:
Implementation 1:
实现1:
function reverse(s) {
var o = '';
for (var i = s.length - 1; i >= 0; i--)
o += s[i];
return o;
}
Implementation 2:
实现2:
function reverse(s) {
var o = [];
for (var i = s.length - 1, j = 0; i >= 0; i--, j++)
o[j] = s[i];
return o.join('');
}
Implementation 3:
实现3:
function reverse(s) {
var o = [];
for (var i = 0, len = s.length; i <= len; i++)
o.push(s.charAt(len - i));
return o.join('');
}
Implementation 4:
实现4:
function reverse(s) {
return s.split('').reverse().join('');
}
Implementation 5:
实现5:
function reverse(s) {
var i = s.length,
o = '';
while (i > 0) {
o += s.substring(i - 1, i);
i--;
}
return o;
}
Implementation 6:
实现6:
function reverse(s) {
for (var i = s.length - 1, o = ''; i >= 0; o += s[i--]) { }
return o;
}
Implementation 7:
实现7:
function reverse(s) {
return (s === '') ? '' : reverse(s.substr(1)) + s.charAt(0);
}
Implementation 8:
实现8:
function reverse(s) {
function rev(s, len, o) {
return (len === 0) ? o : rev(s, --len, (o += s[len]));
};
return rev(s, s.length, '');
}
Implementation 9:
实现9:
function reverse(s) {
s = s.split('');
var len = s.length,
halfIndex = Math.floor(len / 2) - 1,
tmp;
for (var i = 0; i <= halfIndex; i++) {
tmp = s[len - i - 1];
s[len - i - 1] = s[i];
s[i] = tmp;
}
return s.join('');
}
Implementation 10
实现10
function reverse(s) {
if (s.length < 2)
return s;
var halfIndex = Math.ceil(s.length / 2);
return reverse(s.substr(halfIndex)) +
reverse(s.substr(0, halfIndex));
}
#6
22
First, use Array.from()
to turn a string into an array, then Array.prototype.reverse()
to reverse the array, and then Array.prototype.join()
to make it back a string.
首先,使用array .from()将字符串转换为数组,然后使用array .prototype.reverse()反转数组,然后使用array .prototype.join()将其转换为字符串。
const reverse = str => Array.from(str).reverse().join('');
#7
21
In ECMAScript 6, you can reverse a string even faster without using .split('')
split method, with the spread operator like so:
在ECMAScript 6中,不用.split(") split(")方法就可以更快地反转一个字符串,扩展操作符如下:
var str = [...'racecar'].reverse().join('');
#8
18
Seems like I'm 3 years late to the party...
好像我已经迟到3年了……
Unfortunately you can't as has been pointed out. See Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
不幸的是,你不能像已经指出的那样。JavaScript字符串是不可变的吗?我需要在JavaScript中使用“字符串构建器”吗?
The next best thing you can do is to create a "view" or "wrapper", which takes a string and reimplements whatever parts of the string API you are using, but pretending the string is reversed. For example:
您可以做的下一个最好的事情是创建一个“视图”或“包装器”,它接受一个字符串并重新实现您正在使用的字符串API的任何部分,但是假装字符串是相反的。例如:
var identity = function(x){return x};
function LazyString(s) {
this.original = s;
this.length = s.length;
this.start = 0; this.stop = this.length; this.dir = 1; // "virtual" slicing
// (dir=-1 if reversed)
this._caseTransform = identity;
}
// syntactic sugar to create new object:
function S(s) {
return new LazyString(s);
}
//We now implement a `"...".reversed` which toggles a flag which will change our math:
(function(){ // begin anonymous scope
var x = LazyString.prototype;
// Addition to the String API
x.reversed = function() {
var s = new LazyString(this.original);
s.start = this.stop - this.dir;
s.stop = this.start - this.dir;
s.dir = -1*this.dir;
s.length = this.length;
s._caseTransform = this._caseTransform;
return s;
}
//We also override string coercion for some extra versatility (not really necessary):
// OVERRIDE STRING COERCION
// - for string concatenation e.g. "abc"+reversed("abc")
x.toString = function() {
if (typeof this._realized == 'undefined') { // cached, to avoid recalculation
this._realized = this.dir==1 ?
this.original.slice(this.start,this.stop) :
this.original.slice(this.stop+1,this.start+1).split("").reverse().join("");
this._realized = this._caseTransform.call(this._realized, this._realized);
}
return this._realized;
}
//Now we reimplement the String API by doing some math:
// String API:
// Do some math to figure out which character we really want
x.charAt = function(i) {
return this.slice(i, i+1).toString();
}
x.charCodeAt = function(i) {
return this.slice(i, i+1).toString().charCodeAt(0);
}
// Slicing functions:
x.slice = function(start,stop) {
// lazy chaining version of https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice
if (stop===undefined)
stop = this.length;
var relativeStart = start<0 ? this.length+start : start;
var relativeStop = stop<0 ? this.length+stop : stop;
if (relativeStart >= this.length)
relativeStart = this.length;
if (relativeStart < 0)
relativeStart = 0;
if (relativeStop > this.length)
relativeStop = this.length;
if (relativeStop < 0)
relativeStop = 0;
if (relativeStop < relativeStart)
relativeStop = relativeStart;
var s = new LazyString(this.original);
s.length = relativeStop - relativeStart;
s.start = this.start + this.dir*relativeStart;
s.stop = s.start + this.dir*s.length;
s.dir = this.dir;
//console.log([this.start,this.stop,this.dir,this.length], [s.start,s.stop,s.dir,s.length])
s._caseTransform = this._caseTransform;
return s;
}
x.substring = function() {
// ...
}
x.substr = function() {
// ...
}
//Miscellaneous functions:
// Iterative search
x.indexOf = function(value) {
for(var i=0; i<this.length; i++)
if (value==this.charAt(i))
return i;
return -1;
}
x.lastIndexOf = function() {
for(var i=this.length-1; i>=0; i--)
if (value==this.charAt(i))
return i;
return -1;
}
// The following functions are too complicated to reimplement easily.
// Instead just realize the slice and do it the usual non-in-place way.
x.match = function() {
var s = this.toString();
return s.apply(s, arguments);
}
x.replace = function() {
var s = this.toString();
return s.apply(s, arguments);
}
x.search = function() {
var s = this.toString();
return s.apply(s, arguments);
}
x.split = function() {
var s = this.toString();
return s.apply(s, arguments);
}
// Case transforms:
x.toLowerCase = function() {
var s = new LazyString(this.original);
s._caseTransform = ''.toLowerCase;
s.start=this.start; s.stop=this.stop; s.dir=this.dir; s.length=this.length;
return s;
}
x.toUpperCase = function() {
var s = new LazyString(this.original);
s._caseTransform = ''.toUpperCase;
s.start=this.start; s.stop=this.stop; s.dir=this.dir; s.length=this.length;
return s;
}
})() // end anonymous scope
Demo:
演示:
> r = S('abcABC')
LazyString
original: "abcABC"
__proto__: LazyString
> r.charAt(1); // doesn't reverse string!!! (good if very long)
"B"
> r.toLowerCase() // must reverse string, so does so
"cbacba"
> r.toUpperCase() // string already reversed: no extra work
"CBACBA"
> r + '-demo-' + r // natural coercion, string already reversed: no extra work
"CBAcba-demo-CBAcba"
The kicker -- the following is done in-place by pure math, visiting each character only once, and only if necessary:
踢球者——以下是纯粹的数学运算,只访问每个字符一次,必要时:
> 'demo: ' + S('0123456789abcdef').slice(3).reversed().slice(1,-1).toUpperCase()
"demo: EDCBA987654"
> S('0123456789ABCDEF').slice(3).reversed().slice(1,-1).toLowerCase().charAt(3)
"b"
This yields significant savings if applied to a very large string, if you are only taking a relatively small slice thereof.
如果应用到一个非常大的字符串中,如果只取其中的一个相对较小的部分,则会产生显著的节省。
Whether this is worth it (over reversing-as-a-copy like in most programming languages) highly depends on your use case and how efficiently you reimplement the string API. For example if all you want is to do string index manipulation, or take small slice
s or substr
s, this will save you space and time. If you're planning on printing large reversed slices or substrings however, the savings may be small indeed, even worse than having done a full copy. Your "reversed" string will also not have the type string
, though you might be able to fake this with prototyping.
这是否值得(在大多数编程语言中都是这样),很大程度上取决于您的用例和重新实现string API的效率。例如,如果您想做的只是字符串索引操作,或者取小片或分段,这将节省您的空间和时间。如果您打算打印大的反向切片或子字符串,那么可能会节省很多,甚至比完全复制更糟糕。您的“反向”字符串也没有类型字符串,尽管您可以使用原型来伪造它。
The above demo implementation creates a new object of type ReversedString. It is prototyped, and therefore fairly efficient, with almost minimal work and minimal space overhead (prototype definitions are shared). It is a lazy implementation involving deferred slicing. Whenever you perform a function like .slice
or .reversed
, it will perform index mathematics. Finally when you extract data (by implicitly calling .toString()
or .charCodeAt(...)
or something), it will apply those in a "smart" manner, touching the least data possible.
上面的演示实现创建一个反向字符串类型的新对象。它是原型的,因此非常高效,工作几乎很少,空间开销也很小(原型定义是共享的)。它是一个延迟实现,涉及延迟切片。当你执行一个函数如.slice或.reverse,它将执行索引数学。最后,当您提取数据时(通过隐式调用. tostring()或. charcodeat(…)或其他东西),它将以“智能”的方式应用这些数据,从而尽可能地触及最少的数据。
Note: the above string API is an example, and may not be implemented perfectly. You also can use just 1-2 functions which you need.
注意:上面的字符串API就是一个例子,可能不能很好地实现。您还可以使用您需要的1-2个函数。
#9
8
During an interview, I was asked to reverse a string without using any variables or native methods. This is my favorite implementation:
在一次采访中,我被要求在不使用任何变量或本机方法的情况下反转字符串。这是我最喜欢的实现:
function reverseString(str) {
return str === '' ? '' : reverseString(str.slice(1)) + str[0];
}
#10
6
This is the easiest way I think
这是我认为最简单的方法。
var reverse = function(str) {
var arr = [];
for (var i = 0, len = str.length; i <= len; i++) {
arr.push(str.charAt(len - i))
}
return arr.join('');
}
console.log(reverse('I want a ????'));
#11
5
I know that this is an old question that has been well answered, but for my own amusement I wrote the following reverse function and thought I would share it in case it was useful for anyone else. It handles both surrogate pairs and combining marks:
我知道这个老问题已经得到了很好的回答,但为了我自己的乐趣,我写下了下面的逆函数,并认为如果它对任何人都有用,我将分享它。它处理代理对和组合标记:
function StringReverse (str)
{
var charArray = [];
for (var i = 0; i < str.length; i++)
{
if (i+1 < str.length)
{
var value = str.charCodeAt(i);
var nextValue = str.charCodeAt(i+1);
if ( ( value >= 0xD800 && value <= 0xDBFF
&& (nextValue & 0xFC00) == 0xDC00) // Surrogate pair)
|| (nextValue >= 0x0300 && nextValue <= 0x036F)) // Combining marks
{
charArray.unshift(str.substring(i, i+2));
i++; // Skip the other half
continue;
}
}
// Otherwise we just have a rogue surrogate marker or a plain old character.
charArray.unshift(str[i]);
}
return charArray.join('');
}
All props to Mathias, Punycode, and various other references for schooling me on the complexities of character encoding in JavaScript.
Mathias, Punycode以及其他各种各样的参考资料都帮助我了解了JavaScript中字符编码的复杂性。
#12
5
var str = 'sample string';
[].map.call(str, function(x) {
return x;
}).reverse().join('');
OR
或
var str = 'sample string';
console.log(str.split('').reverse().join(''));
// Output: 'gnirts elpmas'
/ /输出:“gnirts elpmas”
#13
2
The real answer is: you can't reverse it in place, but you can create a new string that is the reverse.
真正的答案是:您不能在适当的位置反转它,但是您可以创建一个相反的新字符串。
Just as an exercise to play with recursion: sometimes when you go to an interview, the interviewer may ask you how to do this using recursion, and I think the "preferred answer" might be "I would rather not do this in recursion as it can easily cause a stack overflow" (because it is O(n)
rather than O(log n)
. If it is O(log n)
, it is quite difficult to get a stack overflow -- 4 billion items could be handled by a stack level of 32, as 2 ** 32 is 4294967296. But if it is O(n)
, then it can easily get a stack overflow.
只是作为练习玩递归:有时当你去面试,面试官可能会问你如何使用递归,这样做我认为“优先回答“可能”我宁愿不做这个递归,因为它可以很容易地导致堆栈溢出”(因为它是O(n),而不是O(log n)。如果是O(log n),是很难得到一个堆栈溢出,40亿件可以由一个堆栈级别的32岁,2 * * 32是4294967296。但是如果它是O(n),那么它很容易得到堆栈溢出。
Sometimes the interviewer will still ask you, "just as an exercise, why don't you still write it using recursion?" And here it is:
有时面试官仍然会问你:“作为练习,你为什么不使用递归来写呢?”这是:
String.prototype.reverse = function() {
if (this.length <= 1) return this;
else return this.slice(1).reverse() + this.slice(0,1);
}
test run:
测试运行:
var s = "";
for(var i = 0; i < 1000; i++) {
s += ("apple" + i);
}
console.log(s.reverse());
output:
输出:
999elppa899elppa...2elppa1elppa0elppa
To try getting a stack overflow, I changed 1000
to 10000
in Google Chrome, and it reported:
为了获得堆栈溢出,我将谷歌Chrome中的1000改为10000,它报告:
RangeError: Maximum call stack size exceeded
#14
2
Strings themselves are immutable, but you can easily create a reversed copy with the following code:
字符串本身是不可变的,但是您可以使用以下代码轻松创建一个反向副本:
function reverseString(str) {
var strArray = str.split("");
strArray.reverse();
var strReverse = strArray.join("");
return strReverse;
}
reverseString("hello");
#15
2
//es6
//array.from
const reverseString = (string) => Array.from(string).reduce((a, e) => e + a);
//split
const reverseString = (string) => string.split('').reduce((a, e) => e + a);
//split problem
"????????".split('')[0] === Array.from("????????")[0] // "�" === "????" => false
"????????????".split('')[0] === Array.from("????????????")[0] // "�" === "????" => false
#16
2
In ES6, you have one more option
在ES6中,您还有一个选项
function reverseString (str) {
return [...str].reverse().join('')
}
reverseString('Hello');
#17
1
function reverseString(string) {
var reversedString = "";
var stringLength = string.length - 1;
for (var i = stringLength; i >= 0; i--) {
reversedString += string[i];
}
return reversedString;
}
#18
1
without converting string to array;
不将字符串转换为数组;
String.prototype.reverse = function() {
var ret = "";
var size = 0;
for (var i = this.length - 1; -1 < i; i -= size) {
if (
'\uD800' <= this[i - 1] && this[i - 1] <= '\uDBFF' &&
'\uDC00' <= this[i] && this[i] <= '\uDFFF'
) {
size = 2;
ret += this[i - 1] + this[i];
} else {
size = 1;
ret += this[i];
}
}
return ret;
}
console.log('anãnam anañam' === 'mañana mañana'.reverse());
using Array.reverse without converting characters to code points;
使用数组。不将字符转换为代码点的反向操作;
String.prototype.reverse = function() {
var array = this.split("").reverse();
for (var i = 0; i < this.length; ++i) {
if (
'\uD800' <= this[i - 1] && this[i - 1] <= '\uDBFF' &&
'\uDC00' <= this[i] && this[i] <= '\uDFFF'
) {
array[i - 1] = array[i - 1] + array[i];
array[i] = array[i - 1].substr(0, 1);
array[i - 1] = array[i - 1].substr(1, 1);
}
}
return array.join("");
}
console.log('anãnam anañam' === 'mañana mañana'.reverse());
#19
1
I think String.prototype.reverse is a good way to solve this problem; the code as below;
我认为String.prototype。逆向是解决这一问题的好办法;下面的代码;
String.prototype.reverse = function() {
return this.split('').reverse().join('');
}
var str = 'this is a good example for string reverse';
str.reverse();
-> "esrever gnirts rof elpmaxe doog a si siht";
#20
1
Using Array functions,
使用数组函数,
String.prototype.reverse = function(){
return [].reduceRight.call(this, function(last, secLast){return last + secLast});
}
#21
1
var str = "my name is saurabh ";
var empStr='',finalString='';
var chunk=[];
function reverse(str){
var i,j=0,n=str.length;
for(i=0;i<n;++i){
if(str[i]===' '){
chunk[j]=empStr;
empStr = '';
j++;
}else{
empStr=empStr+str[i];
}
}
for(var z=chunk.length-1;z>=0;z--){
finalString = finalString +' '+ chunk[z];
console.log(finalString);
}
return true;
}
reverse(str);
#22
1
My own original attempt...
我自己的最初的尝试……
var str = "The Car";
function reverseStr(str) {
var reversed = "";
var len = str.length;
for (var i = 1; i < (len + 1); i++) {
reversed += str[len - i];
}
return reversed;
}
var strReverse = reverseStr(str);
console.log(strReverse);
// "raC ehT"
http://jsbin.com/bujiwo/19/edit?js,console,output
http://jsbin.com/bujiwo/19/edit?js,控制台输出
#23
1
Keep it DRY and simple silly!!
保持干燥和简单愚蠢!!
function reverse(s){
let str = s;
var reverse = '';
for (var i=str.length;i>0;i--){
var newstr = str.substring(0,i)
reverse += newstr.substr(-1,1)
}
return reverse;
}
#24
1
OK, pretty simple, you can create a function with a simple loop to do the string reverse for you without using reverse()
, charAt()
etc like this:
很简单,你可以用一个简单的循环创建一个函数来为你做字符串反转,而不用像这样使用reverse(), charAt()等:
For example you have this string:
例如,你有这个字符串:
var name = "*";
Create a function like this, I call it reverseString
...
创建这样的函数,我称之为reverseString…
function reverseString(str) {
if(!str.trim() || 'string' !== typeof str) {
return;
}
let l=str.length, s='';
while(l > 0) {
l--;
s+= str[l];
}
return s;
}
And you can call it like:
你可以这样称呼它:
reverseString(name);
And the result will be:
结果是:
"wolfrevOkcatS"
#25
1
If you don't want to use any built in function. Try this
如果你不想使用任何内置函数。试试这个
var string = 'abcdefg';
var newstring = '';
for(let i = 0; i < string.length; i++){
newstring = string[i] += newstring
}
console.log(newstring)
#26
0
Another variation (does it work with IE?):
另一种变体(与IE兼容吗?)
String.prototype.reverse = function() {
for (i=1,s=""; i<=this.length; s+=this.substr(-i++,1)) {}
return s;
}
EDIT:
编辑:
This is without the use of built-in functions:
这没有使用内置函数:
String.prototype.reverse = function() {
for (i=this[-1],s=""; i>=0; s+=this[i--]) {}
return s;
}
Note: this[-1] holds a length of the string.
注意:这个[-1]包含字符串的长度。
However it's not possible to reverse the string in place, since the assignment to individual array elements doesn't work with String object (protected?). I.e. you can do assigns, but the resulting string doesn't change.
但是,不可能在适当的位置反转字符串,因为分配给单个数组元素的任务不能使用string对象(受保护吗?)。也就是说,你可以做赋值,但是结果的字符串不会改变。
#27
0
var str = "IAMA JavaScript Developer";
var a=str.split(''), b = a.length;
for (var i=0; i<b; i++) {
a.unshift(a.splice(1+i,1).shift())
}
a.shift();
alert(a.join(''));
#28
0
function reverse_string(string)
{
var string;
var len = string.length;
var stringExp = string.split('');
var i;
for (i = len-1; i >=0;i--)
{
var result = document.write(stringExp[i]);
}
return result;
}
reverse_string("This is a reversed string");
//outputs: gnirts desrever a si sihT
//输出:gnirts发一个si sihT
#29
0
function reverse(str){
var s = "";
for (var i = str.length - 1; i >= 0; i--){
s += str[i];
}
return s;
};
reverse("your string comes here")
#30
0
The below might help anyone that is looking to reverse a string recursively. Was asked to do this in a recent job interview using functional programming style:
下面的代码可以帮助任何想要递归地反转字符串的人。在最近的一次工作面试中,他被要求使用函数式编程风格:
var reverseStr = function(str) {
return (str.length > 0) ? str[str.length - 1] + reverseStr(str.substr(0, str.length - 1)) : '';
};
//tests
console.log(reverseStr('setab retsam')); //master bates
#1
640
As long as you're dealing with simple ASCII characters, and you're happy to use built-in functions, this will work:
只要您处理的是简单的ASCII字符,并且您很乐意使用内置函数,这将会工作:
function reverse(s){
return s.split("").reverse().join("");
}
If you need a solution that supports UTF-16 or other multi-byte characters, be aware that this function will give invalid unicode strings, or valid strings that look funny. You might want to consider this answer instead.
如果您需要一个支持UTF-16或其他多字节字符的解决方案,请注意这个函数将给出无效的unicode字符串,或者看起来很有趣的有效字符串。你可能想要考虑这个答案。
#2
371
The following technique (or similar) is commonly used to reverse a string in JavaScript:
下面的技术(或类似的)通常用于在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 ???? bar');
// → 'rab �� oof'
// Where did the `????` symbol go? Whoops!
If you’re wondering why this happens, read up on JavaScript’s internal character encoding. (TL;DR: ????
is an astral symbol, and JavaScript exposes it as two separate code units.)
如果您想知道为什么会发生这种情况,请阅读JavaScript的内部字符编码。(TL;DR:????是一个星体symbol,和JavaScript units.)暴露了它作为两个单独的代码
But there’s more:
但还有更多:
// To see which symbols are being used here, check:
// http://mothereff.in/js-escapes#1ma%C3%B1ana%20man%CC%83ana
naiveReverse('mañana mañana');
// → 'anãnam anañam'
// Wait, so now the tilde is applied to the `a` instead of the `n`? WAT.
A good string to test string reverse implementations is the following:
测试字符串反向实现的好字符串如下:
'foo ???? bar mañana mañana'
Why? Because it contains an astral symbol (????
) (which are represented by surrogate pairs in JavaScript) and a combining mark (the ñ
in the last mañana
actually consists of two symbols: U+006E LATIN SMALL LETTER N and U+0303 COMBINING TILDE).
为什么?因为它包含了一个星体象征(????)(which由代理对JavaScript)和结合马克(the ñ过去mañana实际上包含两个symbols:U+006E拉丁小写字母N和U+0303结合TILDE).
The order in which surrogate pairs appear cannot be reversed, else the astral symbol won’t show up anymore in the ‘reversed’ string. That’s why you saw those ��
marks in the output for the previous example.
代理对出现的顺序不能反转,否则星体符号将不会再出现在“反转”字符串中。这就是为什么你看到这些��标志前面的示例输出。
Combining marks always get applied to the previous symbol, so you have to treat both the main symbol (U+006E LATIN SMALL LETTER N) as the combining mark (U+0303 COMBINING TILDE) as a whole. Reversing their order will cause the combining mark to be paired with another symbol in the string. That’s why the example output had ã
instead of ñ
.
组合标记总是应用于前面的符号,所以您必须将主符号(U+006E拉丁小字母N)作为组合标记(U+0303组合TILDE)作为一个整体。反转它们的顺序将使组合标记与字符串中的另一个符号配对。这就是为什么示例输出̃代替n。
Hopefully, this explains why all the answers posted so far are wrong.
希望这能解释为什么到目前为止所有的答案都是错误的。
To answer your initial question — how to [properly] reverse a string in JavaScript —, I’ve written a small JavaScript library that is capable of Unicode-aware string reversal. It doesn’t have any of the issues I just mentioned. The library is called Esrever; its code is on GitHub, and it works in pretty much any JavaScript environment. It comes with a shell utility/binary, so you can easily reverse strings from your terminal if you want.
为了回答您的第一个问题——如何[正确地]反转JavaScript中的字符串——我编写了一个小的JavaScript库,它能够反转单点感知的字符串。它没有我刚才提到的任何问题。这个图书馆叫做Esrever;它的代码在GitHub上,几乎可以在任何JavaScript环境中使用。它附带一个shell实用程序/二进制文件,因此如果您愿意,可以很容易地从终端反转字符串。
var input = 'foo ???? bar mañana mañana';
esrever.reverse(input);
// → 'anañam anañam rab ???? oof'
As for the “in-place” part, see the other answers.
至于“就地”部分,请参阅其他答案。
#3
86
String.prototype.reverse=function(){return this.split("").reverse().join("");}
or
或
String.prototype.reverse = function() {
var s = "";
var i = this.length;
while (i>0) {
s += this.substring(i-1,i);
i--;
}
return s;
}
#4
48
The whole "reverse a string in place" is an antiquated interview question C programmers, and people who were interviewed by them (for revenge, maybe?), will ask. Unfortunately, it's the "In Place" part that no longer works because strings in pretty much any managed language (JS, C#, etc) uses immutable strings, thus defeating the whole idea of moving a string without allocating any new memory.
整个“反向字符串到位”是一个过时的面试问题——程序员,以及被他们面试过的人(也许是为了报复?)不幸的是,“到位”部分不再起作用,因为几乎任何托管语言(JS、c#等)中的字符串都使用不可变的字符串,从而挫败了在不分配任何新内存的情况下移动字符串的整个想法。
While the solutions above do indeed reverse a string, they do not do it without allocating more memory, and thus do not satisfy the conditions. You need to have direct access to the string as allocated, and be able to manipulate its original memory location to be able to reverse it in place.
虽然上面的解决方案确实会反转一个字符串,但它们在不分配更多内存的情况下不会这样做,因此不满足条件。您需要直接访问所分配的字符串,并且能够操作其原始内存位置,以便能够在适当的位置上反转它。
Personally, i really hate these kinds of interview questions, but sadly, i'm sure we'll keep seeing them for years to come.
就我个人而言,我真的很讨厌这样的面试问题,但遗憾的是,我相信我们会在未来的几年里一直看到这些问题。
#5
42
Detailed analysis and ten different ways to reverse a string and their performance details.
详细分析和10种不同的方法来反转字符串及其性能细节。
http://eddmann.com/posts/ten-ways-to-reverse-a-string-in-javascript/
http://eddmann.com/posts/ten-ways-to-reverse-a-string-in-javascript/
Perfomance of these implementations:
遵守这些实现:
Best performing implementation(s) per browser
每个浏览器的最佳执行
- Chrome 15 - Implemations 1 and 6
- Chrome 15 -实现1和6。
- Firefox 7 - Implementation 6
- Firefox 7 -实现6。
- IE 9 - Implementation 4
- IE 9 -实现4
- Opera 12 - Implementation 9
- Opera 12 -实现9。
Here are those implementations:
这里是这些实现:
Implementation 1:
实现1:
function reverse(s) {
var o = '';
for (var i = s.length - 1; i >= 0; i--)
o += s[i];
return o;
}
Implementation 2:
实现2:
function reverse(s) {
var o = [];
for (var i = s.length - 1, j = 0; i >= 0; i--, j++)
o[j] = s[i];
return o.join('');
}
Implementation 3:
实现3:
function reverse(s) {
var o = [];
for (var i = 0, len = s.length; i <= len; i++)
o.push(s.charAt(len - i));
return o.join('');
}
Implementation 4:
实现4:
function reverse(s) {
return s.split('').reverse().join('');
}
Implementation 5:
实现5:
function reverse(s) {
var i = s.length,
o = '';
while (i > 0) {
o += s.substring(i - 1, i);
i--;
}
return o;
}
Implementation 6:
实现6:
function reverse(s) {
for (var i = s.length - 1, o = ''; i >= 0; o += s[i--]) { }
return o;
}
Implementation 7:
实现7:
function reverse(s) {
return (s === '') ? '' : reverse(s.substr(1)) + s.charAt(0);
}
Implementation 8:
实现8:
function reverse(s) {
function rev(s, len, o) {
return (len === 0) ? o : rev(s, --len, (o += s[len]));
};
return rev(s, s.length, '');
}
Implementation 9:
实现9:
function reverse(s) {
s = s.split('');
var len = s.length,
halfIndex = Math.floor(len / 2) - 1,
tmp;
for (var i = 0; i <= halfIndex; i++) {
tmp = s[len - i - 1];
s[len - i - 1] = s[i];
s[i] = tmp;
}
return s.join('');
}
Implementation 10
实现10
function reverse(s) {
if (s.length < 2)
return s;
var halfIndex = Math.ceil(s.length / 2);
return reverse(s.substr(halfIndex)) +
reverse(s.substr(0, halfIndex));
}
#6
22
First, use Array.from()
to turn a string into an array, then Array.prototype.reverse()
to reverse the array, and then Array.prototype.join()
to make it back a string.
首先,使用array .from()将字符串转换为数组,然后使用array .prototype.reverse()反转数组,然后使用array .prototype.join()将其转换为字符串。
const reverse = str => Array.from(str).reverse().join('');
#7
21
In ECMAScript 6, you can reverse a string even faster without using .split('')
split method, with the spread operator like so:
在ECMAScript 6中,不用.split(") split(")方法就可以更快地反转一个字符串,扩展操作符如下:
var str = [...'racecar'].reverse().join('');
#8
18
Seems like I'm 3 years late to the party...
好像我已经迟到3年了……
Unfortunately you can't as has been pointed out. See Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
不幸的是,你不能像已经指出的那样。JavaScript字符串是不可变的吗?我需要在JavaScript中使用“字符串构建器”吗?
The next best thing you can do is to create a "view" or "wrapper", which takes a string and reimplements whatever parts of the string API you are using, but pretending the string is reversed. For example:
您可以做的下一个最好的事情是创建一个“视图”或“包装器”,它接受一个字符串并重新实现您正在使用的字符串API的任何部分,但是假装字符串是相反的。例如:
var identity = function(x){return x};
function LazyString(s) {
this.original = s;
this.length = s.length;
this.start = 0; this.stop = this.length; this.dir = 1; // "virtual" slicing
// (dir=-1 if reversed)
this._caseTransform = identity;
}
// syntactic sugar to create new object:
function S(s) {
return new LazyString(s);
}
//We now implement a `"...".reversed` which toggles a flag which will change our math:
(function(){ // begin anonymous scope
var x = LazyString.prototype;
// Addition to the String API
x.reversed = function() {
var s = new LazyString(this.original);
s.start = this.stop - this.dir;
s.stop = this.start - this.dir;
s.dir = -1*this.dir;
s.length = this.length;
s._caseTransform = this._caseTransform;
return s;
}
//We also override string coercion for some extra versatility (not really necessary):
// OVERRIDE STRING COERCION
// - for string concatenation e.g. "abc"+reversed("abc")
x.toString = function() {
if (typeof this._realized == 'undefined') { // cached, to avoid recalculation
this._realized = this.dir==1 ?
this.original.slice(this.start,this.stop) :
this.original.slice(this.stop+1,this.start+1).split("").reverse().join("");
this._realized = this._caseTransform.call(this._realized, this._realized);
}
return this._realized;
}
//Now we reimplement the String API by doing some math:
// String API:
// Do some math to figure out which character we really want
x.charAt = function(i) {
return this.slice(i, i+1).toString();
}
x.charCodeAt = function(i) {
return this.slice(i, i+1).toString().charCodeAt(0);
}
// Slicing functions:
x.slice = function(start,stop) {
// lazy chaining version of https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice
if (stop===undefined)
stop = this.length;
var relativeStart = start<0 ? this.length+start : start;
var relativeStop = stop<0 ? this.length+stop : stop;
if (relativeStart >= this.length)
relativeStart = this.length;
if (relativeStart < 0)
relativeStart = 0;
if (relativeStop > this.length)
relativeStop = this.length;
if (relativeStop < 0)
relativeStop = 0;
if (relativeStop < relativeStart)
relativeStop = relativeStart;
var s = new LazyString(this.original);
s.length = relativeStop - relativeStart;
s.start = this.start + this.dir*relativeStart;
s.stop = s.start + this.dir*s.length;
s.dir = this.dir;
//console.log([this.start,this.stop,this.dir,this.length], [s.start,s.stop,s.dir,s.length])
s._caseTransform = this._caseTransform;
return s;
}
x.substring = function() {
// ...
}
x.substr = function() {
// ...
}
//Miscellaneous functions:
// Iterative search
x.indexOf = function(value) {
for(var i=0; i<this.length; i++)
if (value==this.charAt(i))
return i;
return -1;
}
x.lastIndexOf = function() {
for(var i=this.length-1; i>=0; i--)
if (value==this.charAt(i))
return i;
return -1;
}
// The following functions are too complicated to reimplement easily.
// Instead just realize the slice and do it the usual non-in-place way.
x.match = function() {
var s = this.toString();
return s.apply(s, arguments);
}
x.replace = function() {
var s = this.toString();
return s.apply(s, arguments);
}
x.search = function() {
var s = this.toString();
return s.apply(s, arguments);
}
x.split = function() {
var s = this.toString();
return s.apply(s, arguments);
}
// Case transforms:
x.toLowerCase = function() {
var s = new LazyString(this.original);
s._caseTransform = ''.toLowerCase;
s.start=this.start; s.stop=this.stop; s.dir=this.dir; s.length=this.length;
return s;
}
x.toUpperCase = function() {
var s = new LazyString(this.original);
s._caseTransform = ''.toUpperCase;
s.start=this.start; s.stop=this.stop; s.dir=this.dir; s.length=this.length;
return s;
}
})() // end anonymous scope
Demo:
演示:
> r = S('abcABC')
LazyString
original: "abcABC"
__proto__: LazyString
> r.charAt(1); // doesn't reverse string!!! (good if very long)
"B"
> r.toLowerCase() // must reverse string, so does so
"cbacba"
> r.toUpperCase() // string already reversed: no extra work
"CBACBA"
> r + '-demo-' + r // natural coercion, string already reversed: no extra work
"CBAcba-demo-CBAcba"
The kicker -- the following is done in-place by pure math, visiting each character only once, and only if necessary:
踢球者——以下是纯粹的数学运算,只访问每个字符一次,必要时:
> 'demo: ' + S('0123456789abcdef').slice(3).reversed().slice(1,-1).toUpperCase()
"demo: EDCBA987654"
> S('0123456789ABCDEF').slice(3).reversed().slice(1,-1).toLowerCase().charAt(3)
"b"
This yields significant savings if applied to a very large string, if you are only taking a relatively small slice thereof.
如果应用到一个非常大的字符串中,如果只取其中的一个相对较小的部分,则会产生显著的节省。
Whether this is worth it (over reversing-as-a-copy like in most programming languages) highly depends on your use case and how efficiently you reimplement the string API. For example if all you want is to do string index manipulation, or take small slice
s or substr
s, this will save you space and time. If you're planning on printing large reversed slices or substrings however, the savings may be small indeed, even worse than having done a full copy. Your "reversed" string will also not have the type string
, though you might be able to fake this with prototyping.
这是否值得(在大多数编程语言中都是这样),很大程度上取决于您的用例和重新实现string API的效率。例如,如果您想做的只是字符串索引操作,或者取小片或分段,这将节省您的空间和时间。如果您打算打印大的反向切片或子字符串,那么可能会节省很多,甚至比完全复制更糟糕。您的“反向”字符串也没有类型字符串,尽管您可以使用原型来伪造它。
The above demo implementation creates a new object of type ReversedString. It is prototyped, and therefore fairly efficient, with almost minimal work and minimal space overhead (prototype definitions are shared). It is a lazy implementation involving deferred slicing. Whenever you perform a function like .slice
or .reversed
, it will perform index mathematics. Finally when you extract data (by implicitly calling .toString()
or .charCodeAt(...)
or something), it will apply those in a "smart" manner, touching the least data possible.
上面的演示实现创建一个反向字符串类型的新对象。它是原型的,因此非常高效,工作几乎很少,空间开销也很小(原型定义是共享的)。它是一个延迟实现,涉及延迟切片。当你执行一个函数如.slice或.reverse,它将执行索引数学。最后,当您提取数据时(通过隐式调用. tostring()或. charcodeat(…)或其他东西),它将以“智能”的方式应用这些数据,从而尽可能地触及最少的数据。
Note: the above string API is an example, and may not be implemented perfectly. You also can use just 1-2 functions which you need.
注意:上面的字符串API就是一个例子,可能不能很好地实现。您还可以使用您需要的1-2个函数。
#9
8
During an interview, I was asked to reverse a string without using any variables or native methods. This is my favorite implementation:
在一次采访中,我被要求在不使用任何变量或本机方法的情况下反转字符串。这是我最喜欢的实现:
function reverseString(str) {
return str === '' ? '' : reverseString(str.slice(1)) + str[0];
}
#10
6
This is the easiest way I think
这是我认为最简单的方法。
var reverse = function(str) {
var arr = [];
for (var i = 0, len = str.length; i <= len; i++) {
arr.push(str.charAt(len - i))
}
return arr.join('');
}
console.log(reverse('I want a ????'));
#11
5
I know that this is an old question that has been well answered, but for my own amusement I wrote the following reverse function and thought I would share it in case it was useful for anyone else. It handles both surrogate pairs and combining marks:
我知道这个老问题已经得到了很好的回答,但为了我自己的乐趣,我写下了下面的逆函数,并认为如果它对任何人都有用,我将分享它。它处理代理对和组合标记:
function StringReverse (str)
{
var charArray = [];
for (var i = 0; i < str.length; i++)
{
if (i+1 < str.length)
{
var value = str.charCodeAt(i);
var nextValue = str.charCodeAt(i+1);
if ( ( value >= 0xD800 && value <= 0xDBFF
&& (nextValue & 0xFC00) == 0xDC00) // Surrogate pair)
|| (nextValue >= 0x0300 && nextValue <= 0x036F)) // Combining marks
{
charArray.unshift(str.substring(i, i+2));
i++; // Skip the other half
continue;
}
}
// Otherwise we just have a rogue surrogate marker or a plain old character.
charArray.unshift(str[i]);
}
return charArray.join('');
}
All props to Mathias, Punycode, and various other references for schooling me on the complexities of character encoding in JavaScript.
Mathias, Punycode以及其他各种各样的参考资料都帮助我了解了JavaScript中字符编码的复杂性。
#12
5
var str = 'sample string';
[].map.call(str, function(x) {
return x;
}).reverse().join('');
OR
或
var str = 'sample string';
console.log(str.split('').reverse().join(''));
// Output: 'gnirts elpmas'
/ /输出:“gnirts elpmas”
#13
2
The real answer is: you can't reverse it in place, but you can create a new string that is the reverse.
真正的答案是:您不能在适当的位置反转它,但是您可以创建一个相反的新字符串。
Just as an exercise to play with recursion: sometimes when you go to an interview, the interviewer may ask you how to do this using recursion, and I think the "preferred answer" might be "I would rather not do this in recursion as it can easily cause a stack overflow" (because it is O(n)
rather than O(log n)
. If it is O(log n)
, it is quite difficult to get a stack overflow -- 4 billion items could be handled by a stack level of 32, as 2 ** 32 is 4294967296. But if it is O(n)
, then it can easily get a stack overflow.
只是作为练习玩递归:有时当你去面试,面试官可能会问你如何使用递归,这样做我认为“优先回答“可能”我宁愿不做这个递归,因为它可以很容易地导致堆栈溢出”(因为它是O(n),而不是O(log n)。如果是O(log n),是很难得到一个堆栈溢出,40亿件可以由一个堆栈级别的32岁,2 * * 32是4294967296。但是如果它是O(n),那么它很容易得到堆栈溢出。
Sometimes the interviewer will still ask you, "just as an exercise, why don't you still write it using recursion?" And here it is:
有时面试官仍然会问你:“作为练习,你为什么不使用递归来写呢?”这是:
String.prototype.reverse = function() {
if (this.length <= 1) return this;
else return this.slice(1).reverse() + this.slice(0,1);
}
test run:
测试运行:
var s = "";
for(var i = 0; i < 1000; i++) {
s += ("apple" + i);
}
console.log(s.reverse());
output:
输出:
999elppa899elppa...2elppa1elppa0elppa
To try getting a stack overflow, I changed 1000
to 10000
in Google Chrome, and it reported:
为了获得堆栈溢出,我将谷歌Chrome中的1000改为10000,它报告:
RangeError: Maximum call stack size exceeded
#14
2
Strings themselves are immutable, but you can easily create a reversed copy with the following code:
字符串本身是不可变的,但是您可以使用以下代码轻松创建一个反向副本:
function reverseString(str) {
var strArray = str.split("");
strArray.reverse();
var strReverse = strArray.join("");
return strReverse;
}
reverseString("hello");
#15
2
//es6
//array.from
const reverseString = (string) => Array.from(string).reduce((a, e) => e + a);
//split
const reverseString = (string) => string.split('').reduce((a, e) => e + a);
//split problem
"????????".split('')[0] === Array.from("????????")[0] // "�" === "????" => false
"????????????".split('')[0] === Array.from("????????????")[0] // "�" === "????" => false
#16
2
In ES6, you have one more option
在ES6中,您还有一个选项
function reverseString (str) {
return [...str].reverse().join('')
}
reverseString('Hello');
#17
1
function reverseString(string) {
var reversedString = "";
var stringLength = string.length - 1;
for (var i = stringLength; i >= 0; i--) {
reversedString += string[i];
}
return reversedString;
}
#18
1
without converting string to array;
不将字符串转换为数组;
String.prototype.reverse = function() {
var ret = "";
var size = 0;
for (var i = this.length - 1; -1 < i; i -= size) {
if (
'\uD800' <= this[i - 1] && this[i - 1] <= '\uDBFF' &&
'\uDC00' <= this[i] && this[i] <= '\uDFFF'
) {
size = 2;
ret += this[i - 1] + this[i];
} else {
size = 1;
ret += this[i];
}
}
return ret;
}
console.log('anãnam anañam' === 'mañana mañana'.reverse());
using Array.reverse without converting characters to code points;
使用数组。不将字符转换为代码点的反向操作;
String.prototype.reverse = function() {
var array = this.split("").reverse();
for (var i = 0; i < this.length; ++i) {
if (
'\uD800' <= this[i - 1] && this[i - 1] <= '\uDBFF' &&
'\uDC00' <= this[i] && this[i] <= '\uDFFF'
) {
array[i - 1] = array[i - 1] + array[i];
array[i] = array[i - 1].substr(0, 1);
array[i - 1] = array[i - 1].substr(1, 1);
}
}
return array.join("");
}
console.log('anãnam anañam' === 'mañana mañana'.reverse());
#19
1
I think String.prototype.reverse is a good way to solve this problem; the code as below;
我认为String.prototype。逆向是解决这一问题的好办法;下面的代码;
String.prototype.reverse = function() {
return this.split('').reverse().join('');
}
var str = 'this is a good example for string reverse';
str.reverse();
-> "esrever gnirts rof elpmaxe doog a si siht";
#20
1
Using Array functions,
使用数组函数,
String.prototype.reverse = function(){
return [].reduceRight.call(this, function(last, secLast){return last + secLast});
}
#21
1
var str = "my name is saurabh ";
var empStr='',finalString='';
var chunk=[];
function reverse(str){
var i,j=0,n=str.length;
for(i=0;i<n;++i){
if(str[i]===' '){
chunk[j]=empStr;
empStr = '';
j++;
}else{
empStr=empStr+str[i];
}
}
for(var z=chunk.length-1;z>=0;z--){
finalString = finalString +' '+ chunk[z];
console.log(finalString);
}
return true;
}
reverse(str);
#22
1
My own original attempt...
我自己的最初的尝试……
var str = "The Car";
function reverseStr(str) {
var reversed = "";
var len = str.length;
for (var i = 1; i < (len + 1); i++) {
reversed += str[len - i];
}
return reversed;
}
var strReverse = reverseStr(str);
console.log(strReverse);
// "raC ehT"
http://jsbin.com/bujiwo/19/edit?js,console,output
http://jsbin.com/bujiwo/19/edit?js,控制台输出
#23
1
Keep it DRY and simple silly!!
保持干燥和简单愚蠢!!
function reverse(s){
let str = s;
var reverse = '';
for (var i=str.length;i>0;i--){
var newstr = str.substring(0,i)
reverse += newstr.substr(-1,1)
}
return reverse;
}
#24
1
OK, pretty simple, you can create a function with a simple loop to do the string reverse for you without using reverse()
, charAt()
etc like this:
很简单,你可以用一个简单的循环创建一个函数来为你做字符串反转,而不用像这样使用reverse(), charAt()等:
For example you have this string:
例如,你有这个字符串:
var name = "*";
Create a function like this, I call it reverseString
...
创建这样的函数,我称之为reverseString…
function reverseString(str) {
if(!str.trim() || 'string' !== typeof str) {
return;
}
let l=str.length, s='';
while(l > 0) {
l--;
s+= str[l];
}
return s;
}
And you can call it like:
你可以这样称呼它:
reverseString(name);
And the result will be:
结果是:
"wolfrevOkcatS"
#25
1
If you don't want to use any built in function. Try this
如果你不想使用任何内置函数。试试这个
var string = 'abcdefg';
var newstring = '';
for(let i = 0; i < string.length; i++){
newstring = string[i] += newstring
}
console.log(newstring)
#26
0
Another variation (does it work with IE?):
另一种变体(与IE兼容吗?)
String.prototype.reverse = function() {
for (i=1,s=""; i<=this.length; s+=this.substr(-i++,1)) {}
return s;
}
EDIT:
编辑:
This is without the use of built-in functions:
这没有使用内置函数:
String.prototype.reverse = function() {
for (i=this[-1],s=""; i>=0; s+=this[i--]) {}
return s;
}
Note: this[-1] holds a length of the string.
注意:这个[-1]包含字符串的长度。
However it's not possible to reverse the string in place, since the assignment to individual array elements doesn't work with String object (protected?). I.e. you can do assigns, but the resulting string doesn't change.
但是,不可能在适当的位置反转字符串,因为分配给单个数组元素的任务不能使用string对象(受保护吗?)。也就是说,你可以做赋值,但是结果的字符串不会改变。
#27
0
var str = "IAMA JavaScript Developer";
var a=str.split(''), b = a.length;
for (var i=0; i<b; i++) {
a.unshift(a.splice(1+i,1).shift())
}
a.shift();
alert(a.join(''));
#28
0
function reverse_string(string)
{
var string;
var len = string.length;
var stringExp = string.split('');
var i;
for (i = len-1; i >=0;i--)
{
var result = document.write(stringExp[i]);
}
return result;
}
reverse_string("This is a reversed string");
//outputs: gnirts desrever a si sihT
//输出:gnirts发一个si sihT
#29
0
function reverse(str){
var s = "";
for (var i = str.length - 1; i >= 0; i--){
s += str[i];
}
return s;
};
reverse("your string comes here")
#30
0
The below might help anyone that is looking to reverse a string recursively. Was asked to do this in a recent job interview using functional programming style:
下面的代码可以帮助任何想要递归地反转字符串的人。在最近的一次工作面试中,他被要求使用函数式编程风格:
var reverseStr = function(str) {
return (str.length > 0) ? str[str.length - 1] + reverseStr(str.substr(0, str.length - 1)) : '';
};
//tests
console.log(reverseStr('setab retsam')); //master bates