admin管理员组文章数量:1126304
How do you reverse a string in-place in JavaScript when it is passed to a function with a return statement, without using built-in functions (.reverse()
, .charAt()
etc.)?
How do you reverse a string in-place in JavaScript when it is passed to a function with a return statement, without using built-in functions (.reverse()
, .charAt()
etc.)?
- so, you're not allowed to use .charAt() to get the characters of the string? – Irwin Commented Jun 6, 2009 at 3:27
- 192 You can't. JavaScript strings are immutable, meaning the memory allocated to each cannot be written to, making true "in place" reversals impossible. – Crescent Fresh Commented Jun 6, 2009 at 4:36
- 3 Re: crescentfresh's comment see stackoverflow.com/questions/51185/… – baudtack Commented Jun 6, 2009 at 5:25
- 3 @crescentfresh you should post that as a new answer. – baudtack Commented Jun 6, 2009 at 5:47
- 2 Reverse a string in 3 ways in Javascript – Somnath Muluk Commented Sep 12, 2016 at 7:12
59 Answers
Reset to default 1 2 Next 1006As long as you're dealing with simple ASCII characters, and you're happy to use built-in functions, this will work:
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.
The array expansion operator is Unicode aware:
function reverse(s){
return [...s].reverse().join("");
}
Another Unicode aware solution using split()
, as explained on MDN, is to use a regexp with the u
(Unicode) flag set as a separator.
function reverse(s){
return s.split(/(?:)/u).reverse().join("");
}
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
本文标签:
javascriptHow do you reverse a string inplaceStack Overflow
版权声明:本文标题:javascript - How do you reverse a string in-place? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人,
转载请联系作者并注明出处:http://www.betaflare.com/web/1736666042a1946667.html,
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论