Difference between split(), match(), splice(), substring(), and substr() in JavaScript

In JavaScript, several string manipulation methods are commonly used, and each serves a different purpose. Let's go over the differences with examples as follows.

split()

Split string operations will split a string into an array of substrings based on a specified delimiter.

const sentence = "This is a sample sentence";
const words = sentence.split(" ");
console.log(words);

Output

split JavaScript

match()

Match string operation searches a string for a specified pattern and returns an array of matches.

const sentence = "The cat and the hat";
const matches = sentence.match(/at/g);
console.log(matches);

Output

match JavaScript

splice()

Splice is not a string method whereas it is an array method. Its main operation is to changes the contents of an array by removing or replacing existing elements and/or adding new elements.

const fruits = ["apple", "banana", "orange"];
console.log(fruits);
fruits.splice(1, 1, "grape");
console.log(fruits);

Output

splice JavaScript

substring()

Substring is a string operation that extracts characters from a string between two specified indices.

const sentence = "Jithu Thomas";
console.log(sentence);
const substring = sentence.substring(6,12);
console.log(substring);

Output

substing JavaScript

Substr()

Substr is a string operation that extracts a specified number of characters from a string, starting at a specified index.

const sentence = "JITHU THOMAS";
console.log(sentence);
const substr = sentence.substr(6, 6);
console.log(substr);

Output

substr JavaScript

In a nutshell, the methods are described below:

  • split() is used for breaking a string into an array of substrings based on a delimiter.
  • Match() is used for finding matches based on a specified pattern and returning an array.
  • Splice() is an array method, not a string method. It's used for modifying arrays by adding, removing, or replacing elements.
  • Substring() extracts characters between two specified indices.
  • Substr() extracts a specified number of characters starting from a specified index.

Remember

substring and substr are somewhat similar, but substring uses two indices (start and end), while substr uses a start index and a length. Additionally, please note that the substr method is considered legacy, and it's recommended to use substring or other alternatives for better consistency.