20

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)

ajax333221
  • 11,436
  • 16
  • 61
  • 95
  • 1
    possible duplicate of [How do you get a string to a character array in JavaScript?](http://stackoverflow.com/questions/4547609/how-do-you-get-a-string-to-a-character-array-in-javascript) – hippietrail Feb 13 '15 at 18:20

5 Answers5

52

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
11

Maybe you could use the "Destructuring" feature:

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

Using Array.from is probably more explicit.

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

Array.from

Sebastien
  • 5,506
  • 4
  • 27
  • 37
  • 1
    this is the best answer here, it has good browser support and is more readable than any others – JBis Apr 09 '20 at 19:57
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;
    }
    
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

Mikeumus
  • 3,570
  • 9
  • 40
  • 65