21

I am trying to find a way to split a string for every character on JavaScript, an equivalent to String.ToCharArray() from c#

To later join them with commas.

ex: "012345" after splitting -> "['0','1','2','3','4','5']" after join -> "0,1,2,3,4,5"

So far what I have come across is to loop on every character and manually add the commas (I think this is very slow)

1

5 Answers 5

53

This is a much simpler way to do it:

"012345".split('').join(',')

The same thing, except with comments:

"012345".split('') // Splits into chars, returning ["0", "1", "2", "3", "4", "5"]
        .join(',') // Joins each char with a comma, returning "0,1,2,3,4,5"

Notice that I pass an empty string to split(). If you don't pass anything, you'll get an array containing only the original string, rather than an array containing each character.

Alternatively you could pass nothing to join() and it'd use a comma by default, but in cases like this I prefer to be specific.

Don't worry about speed — I'm sure there isn't any appreciable difference. If you're so concerned, there isn't anything wrong with a loop either, though it might be more verbose.

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

1 Comment

so simple, yet so amazing. Thank you
11

Maybe you could use the "Destructuring" feature:

let str = "12345";
//convertion to array:
let strArr = [...str]; // strArr = ["1", "2", "3", "4", "5"]

Comments

5

Using Array.from is probably more explicit.

Array.from("012345").join(',') // returns "0,1,2,3,4,5"

Array.from

1 Comment

this is the best answer here, it has good browser support and is more readable than any others
3
  1. This is a function to make a single word into a char array. Not full proof but does not take much to make it.

    function toCharArray(str){
         charArray =[];
         for(var i=0;i<str.length;i++){
              charArray.push(str[i]);
         }
    
         return charArray;
    }
    

Comments

1

You may use Array's prototype map method called on a string:

Array.prototype.map.call('012345', i => i); 
// ["0", "1", "2", "3", "4", "5"]

See "Using map generically" section of the MDN's Array.prototype.map article here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Comments

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.