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)
The Java String toCharArray() method converts the string to a char array and returns it. The syntax of the toCharArray() method is: string.toCharArray() Here, string is an object of the String class.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
The string in JavaScript can be converted into a character array by using the split() and Array. from() functions.
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.
Maybe you could use the "Destructuring" feature:
let str = "12345";
//convertion to array:
let strArr = [...str]; // strArr = ["1", "2", "3", "4", "5"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With