4 Ways to Extract a Substring from a String in JavaScript

Updated: February 27, 2023 By: Khue Post a comment

Substring extraction means retrieving a portion of a string based on certain criteria. This succinct, practical article will walk you through a few different ways to extract a substring from a given string in JavaScript. No time to waste; let’s kick things off!

Using Regular Expressions

Regular expressions provide a powerful weapon to extract substrings based on patterns. In JavaScript, the String.prototype.match() method can be used with a regular expression to extract substrings.

This example will get all the words whose length is greater than 5:

const str =
  'Welcome to slingacademy.com where there is a lot of code. And, you will find smiles and laughter in every corner of the place.';

// Match all the words whose length is greater than 5
const regex = /\b\w{6,}\b/g;
const result = str.match(regex);
console.log(result);

Output:

[ 'Welcome', 'slingacademy', 'smiles', 'laughter', 'corner' ]

This method is very flexible, and you can customize it to suit your purposes.

Using the substr() method

The String.prototype.substr() method is another option to extract a substring from a string. This method takes 2 arguments: the start index and the length of the substring.

Example:

const str = "He threw three free throws";
const result = str.substr(3, 5);
console.log(result); 

Output:

threw

Even though the substr() method is deprecated, it’s still widely used and loved by the majority of JavaScript developers.

Using the slice() method

You can extract a substring from a string by using the String.prototype.slice() method if you know the start and end position of the substring. The method takes 2 arguments: the start index and the end index. The start index is inclusive, but the end index is exclusive.

Example:

const str = 'In battle, hesitation is defeat.';
const result = str.slice(3, 9);
console.log(result); 

Output:

battle

Using the substring() method

Another method to extract a substring is to use the String.prototype.substring() method. This method also takes 2 arguments: the start index and the end index. The difference between this method and slice() is that substring() cannot accept negative indices.

Example:

const str = 'Behold, strong foes ahead!';
const result = str.substring(0, 6);
console.log(result); 

Output:

Behold

Final Words

You’ve learned more than one technique to extract substrings from a string in JavaScript. The slice(), substring(), and substr() methods are good options when you know the indices of the substring. Regular expressions can provide more flexibility in pattern matching.