Onjsdev

Share


JavaScript Substring Method


By onjsdev

Jan 1st, 2024

JavaScript substring is a string method that allows you to extract a portion of a string and create a new string from that portion.

Syntax

The basic syntax of the substring() method is as follows:

string.substring(startIndex, endIndex)

Here,

  • string is the original string from which we want to extract a substring.
  • startIndex is the index at which the extraction should begin (inclusive), and
  • endIndex is the index at which the extraction should end (exclusive).

As the result of performing the substring() method it returns a new string containing the extracted portion.

Examples

Let's dive into some examples to understand the substring() method better:

Extracting a Substring from a Specific Range:

const str = "Hello, World!";
const substring = str.substring(7, 12);

console.log(substring);  // Output: "World"

In this example, we have a string "Hello, World!". By using the substring() method, we extract the portion starting from the index 7 (inclusive) and ending at the index 12 (exclusive), resulting in the substring "World".

Extracting the Rest of the String:

const str = "Onjsdev Tutorial";
const substring = str.substring(9);

console.log(substring);  // Output: "Tutorial"

In this case, the substring() method is used with only the startIndex parameter. We start the extraction from the index 9, and since we do not provide the endIndex, the method extracts the rest of the string from that point onward. The result is the substring "Tutorial".

Handling Negative Start Index:

const str = "JavaScript is awesome!";
const substring = str.substring(-3);

console.log(substring);  // Output: "JavaScript is awesome!"

Here, the startIndex parameter is -3, which is a negative value. According to the substring() method's behavior, a negative startIndex is treated as 0. Therefore, the entire string is extracted, resulting in the same string as the output.

Conclusion

Javascript substring is a useful string method for extracting substrings from a given string. By providing the starting and ending indices, you can easily create new strings containing specific portions of the original string.

If you want to read more about Javascript string methods, you can see the articles below:

Thank you for reading.