user1752557
user1752557

Reputation: 55

Javascript string to array(if string is without any space)

I have a string for e.g:

        var str = 'abcdef'; 

i want to get it in an array format e.g:

        var a;
        a[0]=a;
        a[1]=b;  and so on.. 

i am aware of split method but in this case of string without any space how can i split as individual character??

Upvotes: 0

Views: 106

Answers (5)

Antony
Antony

Reputation: 15106

var str="abcdef";
var a=new Array;
for (var x=0; x<str.length; x++) {
    a[x] = str.charAt(x);
}
console.log(a);

Upvotes: 0

Talha
Talha

Reputation: 19252

Try using this code:-

var array = str.split('');

Look at the following page to know more about splits.

Javascript split

Upvotes: 0

Chamika Sandamal
Chamika Sandamal

Reputation: 24302

You can access it like this ,

var str='abcdef'; 
alert(str[0]);

or

var str='abcdef'; 
alert(str.charAt(0));

refer following link to chose which is the best way. http://blog.vjeux.com/2009/javascript/dangerous-bracket-notation-for-strings.html

Upvotes: 2

Cris
Cris

Reputation: 13351

var s = "abcdef";
var a;
for (var i = 0; i < s.length; i++) {
    a.push(s.charAt(i));
}

or

 var s = "abcdef";
 var a;
 var a= s.split('');

Upvotes: 0

KooiInc
KooiInc

Reputation: 122906

Use: str.split(''). That will create an array with characters of str as elements.

Upvotes: 3

Related Questions