JavaScript Split Function || JavaScript String

JavaScript

JavaScript Split function is use to break the string into JavaScript array and we write that breaking string in parameter of split function.

If we enter nothing in the split() function parameter than it will make the whole string as one element of an array. Following are the examples to illustrate the split function into more depth.

Example #1:

<!DOCTYPE html>
<html>
<body>
<script>  
var string = "Javascript Programming";
var array = string.split();
console.log(array);
</script>
</body>
</html>

Output:

>["Javascript Programming"]
0: "Javascript Programming"
length: 1

If we want to split an array on the basis of a letter like “a”, where the letter “a” will appear string will split into elements of array.

Example #2:

<!DOCTYPE html>
<html>
<body>
<script>  
var string = "Javascript Programming";
var array = string.split("a");
console.log(array);
</script>
</body>
</html>

Output:

(4) ["J", "v", "script Progr", "mming"]
0: "J"
1: "v"
2: "script Progr"
3: "mming"
length: 4

Example #2:

<!DOCTYPE html>
<html>
<body>
<p id="split"></p>
<script>
var string = "Javascript Programming";
var array = string.split(" ");
document.getElementById("split").innerHTML = array;
</script>
</body>
</html>

Output:

Javascript,Programming

When we pass empty string in the parameter of split function, it will include all the letter in the array even the spaces if there are.As in the below example:

Example #3:

<!DOCTYPE html>
<html>
<body>
<script> 
var string = "Javascript Programming";
var array = string.split("");
console.log(array);
</script>
</body>
</html> 

Output:

(22) ["J", "a", "v", "a", "s", "c", "r", "i", "p", "t", " ", "P", "r", "o", "g", "r", "a", "m", "m", "i", "n", "g"]

In split function the second parameter is size of the array that we want in the result of splitting the string. If the second parameter is 2 , split function will return array of only first two elements.

Example #4:

<!DOCTYPE html>
<html>
<body>
<script>  
var string = "Javascript Programming";
var array = string.split("a",2);
console.log(array);
</script>
</body>
</html>

Output:

(2) ["J", "v"]

  Note: There are many Compilers you can use to run  the HTML.CSS,JAVASCRIPT and PHP codes like Brackets, visual studio and Atom . The best and recommended editor is Visual Studio if you have a System with Sufficient requirements. For more Examples Related CSS,html and Java Script Visit on Coding Academics

Leave a Reply

Your email address will not be published. Required fields are marked *