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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:43:14  来源:igfitidea点击:

How to get nth character in a string in Javascript?

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

回答by Matthew Flaschen

Use the charAtmethod. As far as client or server, it depends on the context. But you should not trust client input.

使用charAt方法。至于客户端或服务器,它取决于上下文。但是您不应该相信客户的输入。

回答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 中完全相同。