JavaScript split

The split() method is used to split a string into an array of substrings, based on a character that divides the parts. The character that divides the parts could be many things, ex – a comma, a slash, a pipe symbol ( | ), or another of your choice.


string.split(separator, limit)

separator – Optional. Specifies the character to use for splitting the string. If omitted, the entire string will be returned

limit – Optional. An integer that specifies the number of splits

Let’s start with a little example that takes a string of characters and splits when it sees the character “-”. That means the delimiter for this example is -. Notice that the split function returns an array that we store into mySplitResult.

<script language="javascript">
function splitString()
var mystring = "learnwebdevelopment-info";
var mySplitResult = mystring.split("-");
alert("The first element is " + mySplitResult[0]);
alert("The second element is " + mySplitResult[1]);

<input type="button" value="Split" onClick="javascript:splitString();">

Output of the above code will be;

The first element is learnwebdevelopment
The second element is info


You can see it in action using the button below:

Posted in Javascript