Sling Academy
Home/JavaScript/4 Ways to Extract a Substring from a String in JavaScript

4 Ways to Extract a Substring from a String in JavaScript

Last updated: February 27, 2023

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.

Next Article: How to Convert a String into an Array in JavaScript

Previous Article: 3 Ways to Reverse a String in JavaScript

Series: JavaScript Strings

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration