Split Function In JavaScript
- We will discover how to split a string in JavaScript in this article. A string object can be divided into substrings by comma-separated values using the Split function. Additionally, it turns the string object into an array of strings, which we may access without using the string object’s value. In this article, we will divide a string using many examples, such as splitting it by a space or another unique character.
Start writing code now :-
Split Syntex :-
– string.split([seperator][, Limit]);
Write the split function’s code as shown below. The string can be divided using the following examples: space, comma, special character.
//Split by Comma//
var topicstr = “How To Use,Split,Function In JavaScript”;
var splitter = topicstr.split(“,”);
document.write(‘Split By Comma Index[0] :- ‘ + splitter[0] + ‘<br>’);
document.write(‘Split By Comma Index[1] :- ‘ + splitter[1] + ‘<br>’);
document.write(‘Split By Comma Index[2] :- ‘ + splitter[2] + ‘<br>’);
//Split By Space
var str = “Java Script”;
var splitter = str.split(” “);
document.write(‘Split by space index[0] :-‘ + splitter[0] + ‘<br>’);
document.write(‘Split by space index[1] :-‘ + splitter[1] + ‘<br>’);
//Splite by Special character
var specialchar = “How To Use@Split@Function In JavaScript”;
var splitter = specialchar.split(“@”);
document.write(‘Split By Spciela Character Index[0] :- ‘ + splitter[0] + ‘<br>’);
document.write(‘split By Special Character Index[1] :- ‘ + splitter[1] + ‘<br>’);
document.write(‘split By Special Character Index[2] :- ‘ + splitter[2] + ‘<br>’);
Summary :-
In the example above, we tried to split a string object by a space, a comma (,), and a special character (@), and then we tried to access the split string using its index, such as “Java Script.” Here, we separated this text by commas, and then we used its index, such as 0 or 1, to retrieve it. The split string’s index is determined by its length.