The String.prototype.split()
function divide the string into array of sub-strings. You can perform other array manipulation on the resultant string.
The syntax for split()
function is given below.
String.split([separator, limit]);
Separator – it is a character that is used to separate the sub-strings. It is optional, however, a separator is required to divide the sub-strings.
Limit – it is the number of characters to be split. This is also optional.
Examples: split() function
Here are few examples of split
function with and without separators.
var Str = "Hello World";
Str.split('');
// result in single character split
//Output - "H","e","l","l","o", " ","W", "o", "r","l","d"
Str.split(' ');
//result in split between works rather than single characters
//Output - "Hello", "World"
Str.split();
//No arguments, the whole array is returned
//Output - Array["Hello World"]
Str.split('', 4);
//Limit set to 4, therefore, split only four letters
//Output - "H","e","l","l"
Example Program: split() function
<!DOCTYPE html>
<html>
<head>
<title>JS: split() Function</title>
<style>
main{
width:60%;
padding:10%;
margin: auto;
text-align:center;
background:rgba(240,144,43,0.6);
}
</style>
</head>
<body>
<main>
<h1 id="out1"></h1>
<h1 id="out2"></h1>
<h1 id="out3"></h1>
<h1 id="out4"></h1>
</main>
<script>
var Str = "Fresh Start";
// result in single character split
document.getElementById("out1").innerHTML = Str.split('');
//result in split between works rather than single characters
document.getElementById("out2").innerHTML = Str.split(' ');
//No arguments, the whole array is returned
document.getElementById("out3").innerHTML = Str.split();
Str.split('', 4);
//Limit set to 4, therefore, split only four letters
document.getElementById("out4").innerHTML = Str.split('',4);
</script>
</body>
</html>