Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
179
rated 0 times [  186] [ 7]  / answers: 1 / hits: 62256  / 13 Years ago, fri, january 6, 2012, 12:00:00

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)


More From » javascript

 Answers
90

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.


[#88186] Thursday, January 5, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rocioblancac

Total Points: 699
Total Questions: 96
Total Answers: 108

Location: Libya
Member since Mon, Dec 7, 2020
4 Years ago
;