JavaScript String substring() Method - JavaScript Tutorial

JavaScript String substring() Method

BLUF: This tutorial on JavaScript String substring() Method provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: JavaScript String substring() Method

Understanding JavaScript String substring() Method is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

The substring function in JavaScript retrieves a segment of a string based on the specified index and produces a new substring. It functions akin to the slice method, but with the distinction that it does not support negative indices. Notably, the original string remains unaltered when using this method.

Syntax

The syntax for the substring method is as follows:

Example

string.substring(start,end)

Parameter

Begin - It denotes the index of the string indicating the starting point for retrieval.

The "end" parameter is not mandatory. It specifies the endpoint where the string extraction stops.

Return

Part of the string.

JavaScript String substring Method Example

Let's explore a few basic instances showcasing the functionality of the substring function.

Example 1

Here is a basic illustration demonstrating how to output a specific section of a string.

Example

<script>

var str="Example";

document.writeln(str.substring(0,4));

</script>

Output:

Example 2

In this instance, we will retrieve a single character from a given string.

Example

<script>

var str="Example";

document.writeln(str.substring(4,5));

</script>

Output:

Example 3

In this instance, we will solely furnish the initial index.

Example

<script>

var str="Example";

document.writeln(str.substring(5));

</script>

Output:

Example 4

In this instance, we will demonstrate calling the method without passing any parameters. In this scenario, the method will return the entire string.

Example

<script>

var str="Example";

document.writeln(str.substring());

</script>

Output:

Output

Example

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience