DrStrangeLove DrStrangeLove - 2 months ago 9x
Javascript Question

How do I split a string into an array of characters?

var s = "overpopulation";
var ar = [];
ar = s.split();

I want to string.split a word into array of characters.

The above code doesn't seem to work - it returns "overpopulation" as Object..

How do i split it into array of characters, if original string doesn't contain commas and whitespace?


You can split on an empty string:

var chars = "overpopulation".split('');

If you just want to access a string in an array-like fashion, you can do that without split:

var s = "overpopulation";
for (var i = 0; i < s.length; i++) {

You can also access each character with its index in the normal fashion:

var s = "overpopulation";

console.log(s[3]); // logs 'r'