0

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??

5 Answers 5

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

3 Comments

Right, but use str.charAt(0)
@lan: Can you explain why. without saying just use this.
See stackoverflow.com/questions/5943726/string-charatx-or-stringx for reasons why charAt should be used.
0
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('');

Comments

0

Try using this code:-

var array = str.split('');

Look at the following page to know more about splits.

Javascript split

Comments

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

1 Comment

You should use str.charAt(x), not str[x]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.