The split() Function is used to split a String into an Array.
<html>
<body>
<script language = "javascript" type = "text/javascript">
var x = "Hello Beautiful World"
var y = x.split(' ')
document.write(y)
</script>
</body>
</html>
So, in the above code, we have a String Hello Beautiful World initialised to a variable x.
var x = "Hello Beautiful World"
-Function1.png)
Then we have used the split() function on the variable x.
var y = x.split(' ')So, the split() function converts the String, Hello Beautiful World to a Array, separated by a space (i.e. ' ').
And initialises the Array to the variable y.
-Function2.png)
So, if you see the above String, Hello Beautiful World. Hello, Beautiful and World are separated by a space (i.e. ' ').
So, a Array is formed with Hello, Beautiful and World.
But what if the Strings are separated by @ or any other symbol.
Say, the below String is separated by @.
"Hello@Beautiful@World"
Now, if you want to form a Array with Hello, Beautiful and World. You can use split() function providing the separator @ as argument.
<html>
<body>
<script language = "javascript" type = "text/javascript">
var x = "Hello@Beautiful@World"
var y = x.split("@")
for (i of y) {
document.write(i, ": ")
}
</script>
</body>
</html>
So, in the above code, we have a String Hello@Beautiful@World initialised to a variable x.
var x = "Hello@Beautiful@World"
-Function3.png)
Then we have used the split() function with the separator @ as argument on the variable x.
var y = x.split("@")So, the split() function converts the String, Hello@Beautiful@World to a Array, separated by the separator (i.e. @).
And initialises the Array to the variable y.
-Function4.png)
In the above example, we have three items in the Array. But what if, you want only two items in the Array.
i.e. For the same String, Hello@Beautiful@World, we just want two items in the Array, Hello and Beautiful
-Function5.png)
We can achieve the above using a second parameter that specifies the number of Array elements.
<html>
<body>
<script language = "javascript" type = "text/javascript">
var x = "Hello@Beautiful@World"
var y = x.split("@", 2)
for (i of y) {
document.write(i, ": ")
}
</script>
</body>
</html>
So, in the above code, we have a String Hello@Beautiful@World initialised to a variable x.
-Function6.png)
Then we have used the split() function with the separator @ and 2 as arguments on the variable x.
var y = x.split("@", 2)So, the split() function converts the String, Hello@Beautiful@World to a Array, separated by the separator (i.e. @).
And initialises the Array to the variable y.
-Function7.png)
And as we can see only Hello and Beautiful is taken omitting World.