How to get character array from string in JavaScript ?
The string in JavaScript can be converted into a character array by using the split() and Array.from() functions.
JavaScript String split() Function: The str.split() function is used to split the given string into an array of strings by separating it into substrings using a specified separator provided in the argument.
Syntax:
str.split(separator, limit)
Example: In this example, we will get a character array from the string using the split() function in Javascript.
html
< body style = "text-align:center;" > < h1 style = "color:green" > GeeksforGeeks </ h1 > < p id = "one" > GeeksforGeeks: A computer science portal </ p > < input type = "button" value = "Click Here!" onclick = "myGeeks()" > < script > function myGeeks() { var str = document.getElementById("one").innerHTML; document.getElementById("one").innerHTML = str.split(""); } </ script > </ body > |
Output:

JavaScript Array.from() Function: The Array.from() function is an inbuilt function in JavaScript that creates a new array instance from a given array. In the case of a string, every alphabet of the string is converted to an element of the new array instance and in the case of integer values, a new array instance simply takes the elements of the given array.
Syntax:
Array.from(str)
Example: In this example, we will get a character array from the string using the Array.from() function in Javascript.
html
< body style = "text-align:center;" > < h1 style = "color:green" > GeeksforGeeks </ h1 > < p id = "one" > GeeksforGeeks: A computer science portal </ p > < input type = "button" value = "Click Here!" onclick = "myGeeks()" > < script > function myGeeks() { var str = document.getElementById("one").innerHTML; document.getElementById("one").innerHTML = Array.from(str); } </ script > </ body > |
Output:

JavaScript Spread Operator: Spread operator allows an iterable to expand in place. In the case of a string, it example string into character and we capture all the characters of a string in an array.
Syntax:
var variableName = [ ...value ];
Example: In this example, we will get a character array from the string using the spread operator in Javascript.
HTML
< body style = "text-align:center;" > < h1 style = "color:green" > GeeksforGeeks </ h1 > < p id = "one" > GeeksforGeeks: A computer science portal </ p > < input type = "button" value = "Click Here!" onclick = "myGeeks()" > < script > function myGeeks() { var str = document.getElementById("one").innerHTML; document.getElementById("one").innerHTML = [...str]; } </ script > </ body > |
Output:

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
Please Login to comment...