JavaScript string.split() Method

Shubham Vora Jan 30, 2023
  1. Syntax of JavaScript string.split() Method
  2. Example Code: Use the string.split() Method to Create Unique Substrings
  3. Example Code: Use the string.split() Method to Limit the Characters or Words for a New Array
JavaScript string.split() Method

The string.split() method is an inbuilt method in JavaScript that is used to split the string by the separator and get an array of words or characters, including punctuation marks. The split() method can limit words or characters in the array, specify words or punctuation marks in the split() method, and remove words and phrases from the string.

Syntax of JavaScript string.split() Method

referenceString.split(separator);
referenceString.split(separator, limit);

Parameters

separator Splits the string into an array of characters based on the seprator.
limit It denotes the size of the array of substrings. If array size increases the limit, it excludes the substrings.

Return

It returns an array of strings based on the separator and limit parameters.

Example Code: Use the string.split() Method to Create Unique Substrings

let str = 'Hello World! Welcome to everyone.';
let regE = str.split(" ");
let arr = str.split("World! Welcome to");
console.log(regE);
console.log(arr);

Output:

Hello,World!,Welcome,to,everyone.
Hello , everyone.

In the example above, we have passed separator with different values to return the substrings.

Example Code: Use the string.split() Method to Limit the Characters or Words for a New Array

let str = 'Hello World!';
let arr = str.split(" ", 1);
let ref = str.split("", 5);
console.log(arr);
console.log(ref);

Output:

'Hello'
'H', 'e', 'l', 'l', 'o'

In the above example, We passed the limit parameter with the separator parameter, which limits the size of the array of substrings returned by the string.split() method.

Author: Shubham Vora
Shubham Vora avatar Shubham Vora avatar

Shubham is a software developer interested in learning and writing about various technologies. He loves to help people by sharing vast knowledge about modern technologies via different platforms such as the DelftStack.com website.

LinkedIn GitHub

Related Article - JavaScript API