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

In the above example, the following JavaScript statement:

let myString = "JavaScript is Fun";

declares a variable myString and assigns it the value of the string "JavaScript is Fun".

Then the following (second) JavaScript statement:

let myArray = myString.split(" ");

declares another variable, myArray, and assigns it the result of calling the split method on myString. The split method splits a string into an array of substrings based on a specified separator. In this case, the separator is a space character, so the resulting array will contain two elements: "JavaScript" and "is".

Finally, using the following (last) JavaScript statement:

document.getElementById("xyz").innerHTML = myArray;

The paragraph element with the id "xyz" is retrieved using the getElementById method. The innerHTML property of that element is then set to the value of myArray. myArray will be converted to a string before being inserted into the HTML because it is an array. The resulting string in this case will be "JavaScript,is" (with a comma separating the two elements).

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

JavaScript split() syntax

The syntax of the split() method in JavaScript is:

string.split(separator, limit)

Both separator (referring to a string or a regular expression) and limit (referring 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 the 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 »


Liked this post? Share it!