JavaScript Substring: Efficient Methods with Examples

JavaScript Substring: An Overview

A substring is a part of a string that is extracted and used separately. In JavaScript, you can easily get a substring using built-in methods. In this article, we will discuss the primary methods for obtaining a substring in JavaScript, along with clear examples for each technique.

Using substring() Method

The substring() method extracts characters from a string between two provided indices and returns the characters as a new string. The method has two optional parameters: start and end. If the end parameter is omitted, the method extracts characters until the end of the string.

const str = 'JavaScript is amazing!';
const result = str.substring(0, 10);
console.log(result); // Output: JavaScript

Using slice() Method

The slice() method works similarly to the substring() method but offers more flexibility. It can handle negative index values as well. If the provided index values are negative, slice() calculates the indices from the end of the string.

const str = 'JavaScript is amazing!';
const result = str.slice(-8, -1);
console.log(result); // Output: amazing

Using substr() Method

The substr() method is another way to get a substring in JavaScript. It takes two parameters: start and length. The method extracts the characters starting at the specified index and of the specified length.

const str = 'JavaScript is amazing!';
const result = str.substr(12, 2);
console.log(result); // Output: is


In this article, we discussed three primary methods for getting a substring in JavaScript: substring(), slice(), and substr(). Each method has its own unique features and can be used depending on your specific requirements. We hope these examples helped you better understand how to obtain substrings in JavaScript.