36

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"...).

How do I get the nth character in the string?

Thanks!

Bonus: How could I do it with Python? Would it be better than doing it client-side?

ana
  • 1,565
  • 4
  • 17
  • 22

3 Answers3

66

Let me summarize the possibilities

given:

var string = "HAI";
/* and */
var index = 1; // number ∈ [0..string.length), rounded down to integer
Free Consulting
  • 4,300
  • 1
  • 29
  • 50
43

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

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
5

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.

harto
  • 89,823
  • 9
  • 47
  • 61