JavaScript Substring - Comprehensive detail with examples

JavaScript Substring - Comprehensive detail with examples

Hello Guys,

Today, we are going to learn about JavaScript Substring function in detail and with examples. We will learn about the subtring() function, how to use JavaScript Substring and best use cases as well.

Let's get started with knowing what a JavaScript Substring is.

What is a JavaScript Substring?

The JavaScript substring function is a very useful feature of JavaScript that allows you to extract a part of a string. The JavaScript Substring function extracts the characters from a string between two positions and returns the new string with extracted characters or values. It takes two parameters to extract substring from start to end exclusively.

Keep in mind a few things before using the JavaScript substring method. If the starting value is greater than the ending value, the parameters will be swapped. (4, 1) = (1, 4)

How to use Substring functions in JavaScript?

The substring() function has a simple syntax to get substrings from the string in JavaScript. Let's see the following examples.

Example 1: How to extract substrings from the beginning of a string in JavaScript?

The following example will explain to you how to extract a substring from a string in javascript with the help of a substring function:

let str = 'JavaScript Substring';

console.log(str.substring(0, 10));

// output: JavaScript

Example 2: How to extract the last characters from a string?

The following example will show you how to extract the last characters from the specified index up to the end of a string in JavaScript.

let str = 'JavaScript Substring';

console.log(str.substring(11));

// output: Substring

Example 3: How to extract substrings from the middle of the string?

The following example will show you how to extract substrings from the middle of a string in JavaScript.

let str = 'JavaScript Substring';

console.log(str.substring(4, 10));

// output: Script

How to get an index of a substring from the string in JavaScript?

To get the indexOf of a substring from the string, you can use JavaScript's builtin function indexOf(). This method will return the first appearance of the specified substring in the string or "-1". Please keep in mind, this method is case-sensitive.

let str = 'JavaScript';

console.log(str.indexOf('Script'));

// output: 4

Conclusion

In this detailed tutorial, we have learnt about how to extract a substring from a string with a substring() JavaScript function. We have seen a few examples as well of extracting substrings from the string in different ways.

I hope this will help you in your next project.

Happy Coding :)

Leave a Comment

Your email address will not be published. Required fields are marked *

Go To Top
×