Skip to content
Related Articles

Related Articles

Improve Article

How to get character array from string in JavaScript?

  • Last Updated : 20 Jul, 2021

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

Using String split() Function: The str.split() function is used to split the given string into array of strings by separating it into substrings using a specified separator provided in the argument.
Syntax:

str.split(separator, limit)

Example:




<!DOCTYPE html>
<html>
  
<head>
    <title>
        String to a character array
    </title>
</head>
  
<body style="text-align:center;">
  
    <h1>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>
  
</html>                    

Output:
Before Clicking the button:

After Clicking the button:

Using Array.from() Function: The Array.from() function is an inbuilt function in JavaScript which creates a new array instance from a given array. In case of a string, every alphabet of the string is converted to an element of the new array instance and in case of integer values, new array instance simple take the elements of the given array.
Syntax:



Array.from(str)

Example:




<!DOCTYPE html>
<html>
  
<head>
    <title>
        String to a character array
    </title>
</head>
  
<body style="text-align:center;">
  
    <h1>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>
  
</html>                    

Output:
Before Clicking the button:

After Clicking the button:

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :