Javascript 如何在Javascript中的字符串中获取第n个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4282798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get nth character in a string in Javascript?
提问by ana
I've a string (let's say "Hello World") and I want to save the first characters of it in different variables (ex. character1 = "H", character2 = "e"...).
我有一个字符串(比如“Hello World”),我想将它的第一个字符保存在不同的变量中(例如 character1 = "H", character2 = "e"...)。
How do I get the nth character in the string?
如何获取字符串中的第 n 个字符?
Thanks!
谢谢!
Bonus: How could I do it with Python? Would it be better than doing it client-side?
奖励:我怎么能用 Python 做到这一点?它会比在客户端做更好吗?
回答by Free Consulting
Let me summarize the possibilities
让我总结一下可能性
given:
给出:
var string = "HAI";
/* and */
var index = 1; // number ∈ [0..string.length), rounded down to integer
string.charAt(index)
returns"A"
(preferred)string[index]
returns"A"
(non-standard)string.substring(index, index+1)
returns"A"
(over-complex solution but works)string.substr(index, 1)
returns"A"
(non-standard approach to above)
string.charAt(index)
退货"A"
(首选)string[index]
退货"A"
(非标准)string.substring(index, index+1)
返回"A"
(过于复杂的解决方案但有效)string.substr(index, 1)
回报"A"
(上述的非标准方法)
回答by Matthew Flaschen
回答by harto
Not sure if this is cross-browser safe, but you can use array-like indexing:
不确定这是否跨浏览器安全,但您可以使用类似数组的索引:
"Hello"[0] -> "H"
The syntax is exactly the same in Python.
语法在 Python 中完全相同。