Open In App

JavaScript String split() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The split() method in JavaScript is used to split a string into an array of substrings based on a specified separator.

String split() Method Syntax: 

str.split(separator, limit);
  • separator: It is used to specify the character, or the regular expression, to use for splitting the string. If the separator is unspecified then the entire string becomes one single array element. The same also happens when the separator is not present in the string. If the separator is an empty string (“”) then every character of the string is separated.
  • limit: Defines the upper limit on the number of splits to be found in the given string. If the string remains unchecked after the limit is reached then it is not reported in the array.

Return value:

This function returns an array of strings that is formed after splitting the given string at each point where the separator occurs. 

String split() Method Example: 

Here is the basic example of the split() method.

JavaScript




// JavaScript Program to illustrate split() function
 
function func() {
    //Original string
    let str = 'Geeks for Geeks'
    let array = str.split("for");
    console.log(array);
}
func();


Output

[ 'Geeks ', ' Geeks' ]



Explanation:

  • JavaScript program defines function func() splitting string ‘Geeks for Geeks’ using “for” as separator.
  • Resulting array [“Geeks “, ” Geeks”] is logged to console.

String split() Method Example:

Here, the function split() creates an array of strings by splitting str wherever ” ” occurs.

JavaScript




// JavaScript Program to illustrate split() function
 
function func() {
    //Original string
    let str = 'It iS a 5r&e@@t Day.'
    let array = str.split(" ");
    console.log(array);
}
func();


Output

[ 'It', 'iS', 'a', '5r&e@@t', 'Day.' ]



Explanation:

  • The string ‘It iS a 5r&e@@t Day.’ is split into an array using a space as the separator.
  • Resulting array: [“It”, “iS”, “a”, “5r&e@@t”, “Day.”].

We have a complete list of Javascript string methods, to check those please go through this Javascript String Complete reference article.

Supported Browsers:



Last Updated : 04 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads