如何在JavaScript中反转字符串? [英] How do you reverse a string in place in JavaScript?
问题描述
当传递给带有return语句的函数时,如何在JavaScript中反转字符串(或就地)?所有没有使用内置功能? .reverse()
, .charAt()
等。
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.
推荐答案
只要您处理简单的ASCII字符,并且您很乐意使用内置函数,这将有效:
As 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("");
}
如果您需要支持UTF-16或其他多字节字符的解决方案,请注意,此函数将提供无效的unicode字符串或有效的字符串。您可能需要考虑此答案。
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.
这篇关于如何在JavaScript中反转字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!