How to Extract a Part of a String in JavaScript

08/01/2021

Contents

In this article, you will learn how to extract a part of a string in JavaScript.

Extracting a part of a string in JavaScript

In JavaScript, you can extract a part of a string using the substring(), substr(), and slice() methods. These methods all return a new string that represents the extracted part of the original string.

Using the substring() method

The substring() method extracts the characters between two specified indices and returns a new string. The method takes two arguments: start and end. The start argument specifies the starting index, and the end argument specifies the ending index (exclusive). If the end argument is omitted, the method extracts the characters from the start index to the end of the string.

Example

const str = "Hello, world!";
const result = str.substring(7, 12);
console.log(result); // "world"

In this example, we extracted the substring “world” from the original string “Hello, world!” using the substring() method.

Using the substr() method

The substr() method extracts a specified number of characters from a string, starting from a specified index, and returns a new string. The method takes two arguments: start and length. The start argument specifies the starting index, and the length argument specifies the number of characters to extract.

Example

const str = "Hello, world!";
const result = str.substr(7, 5);
console.log(result); // "world"

In this example, we extracted the substring “world” from the original string “Hello, world!” using the substr() method.

Using the slice() method

The slice() method extracts a section of a string and returns a new string. The method takes two arguments: start and end. The start argument specifies the starting index, and the end argument specifies the ending index (exclusive). If the end argument is omitted, the method extracts the characters from the start index to the end of the string.

Example

const str = "Hello, world!";
const result = str.slice(7, 12);
console.log(result); // "world"

In this example, we extracted the substring “world” from the original string “Hello, world!” using the slice() method.