Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.ToCharArray() equivalent on JavaScript?

Tags:

javascript

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)

like image 553
ajax333221 Avatar asked Jan 06 '12 17:01

ajax333221


People also ask

What is string toCharArray?

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.

How do I convert a string to an array in JavaScript?

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.

How can one create an array of characters from a string in JavaScript?

The string in JavaScript can be converted into a character array by using the split() and Array. from() functions.


2 Answers

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.

like image 123
BoltClock Avatar answered Oct 14 '22 14:10

BoltClock


Maybe you could use the "Destructuring" feature:

let str = "12345";
//convertion to array:
let strArr = [...str]; // strArr = ["1", "2", "3", "4", "5"]
like image 25
Edgardo Rodriguez Avatar answered Oct 14 '22 15:10

Edgardo Rodriguez