JavaScript Code

String substring() in JavaScript


String substring()

In JavaScript, String.substring() method is used to find the substring of a string which is defined by a specific start index, and an optional length.

Syntax

str.substring(start)
str.substring(start, end)

where

  • str is a string.
  • start is a number.
  • end is a number.

If start and end are less than 0, then they are considered zero.

substring() finds the substring of the given string from given start, to end position, and returns the substring.

Examples

1. substring(start) – where substring is defined by only a specific start index in the string.

let name = 'appleisgreat';
let output = name.substring(6);
console.log(output);

2. substring(start) with start as negative number

let name = 'appleisgreat';
let output = name.substring(-8); //negative start
console.log(output);

3. substring(start, end) – where substring is defined by a specific start index in the string, and a specific end index in the string.

let name = 'appleisgreat';
let output = name.substring(4, 9);
console.log(output);

Copyright @2022