Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get nth character in a string in Javascript?

Tags:

javascript

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?

like image 593
ana Avatar asked Nov 26 '10 05:11

ana


2 Answers

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)
like image 199
Free Consulting Avatar answered Oct 11 '22 08:10

Free Consulting


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

like image 25
Matthew Flaschen Avatar answered Oct 11 '22 10:10

Matthew Flaschen