javascriptstring

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


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

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?


Solution

  • 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++) {
        console.log(s.charAt(i));
    }
    

    You can also access each character with its index using normal array syntax. Note, however, that strings are immutable, which means you can't set the value of a character using this method, and that it isn't supported by IE7 (if that still matters to you).

    var s = "overpopulation";
    
    console.log(s[3]); // logs 'r'