JavaScript split() | Split a String into an Array

The JavaScript split() method is used to split a specified string into an array. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      let myString = "JavaScript is Fun";
      let myArray = myString.split(" ");
      document.getElementById("xyz").innerHTML = myArray;
   </script>
   
</body>
</html>
Output

You can see from the above output, all words of the string, that are JavaScript, is and, Fun are converted into elements of array named myArray.

JavaScript split() Syntax

The syntax of split() method in JavaScript is:

string.split(separator, limit)

Both separator (refers to a string or a regular expression) and limit (refers to a number) arguments are optional.

The separator argument is used to define the way to split the string. And the limit argument is used to limit the number of splits.

Important: Omitting the value of separator argument will return an array containing only one element as the whole string. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      let myString = "JavaScript is Fun";
      let myArray = myString.split();
      document.getElementById("xyz").innerHTML = myArray;
   </script>
   
</body>
</html>
Output

Note: Omitting the limit argument split the whole string.

JavaScript Online Test


« Previous Tutorial Next Tutorial »