Function strSubstring

The strSubstring() method returns the part of the string between the start and end indexes, or to the end of the string.

strSubstring() extracts characters from indexStart up to but not including indexEnd. In particular:

  • If indexEnd is omitted, strSubstring() extracts characters to the end of the string.
  • If indexStart is equal to indexEnd, strSubstring() returns an empty string.
  • If indexStart is greater than indexEnd, then the effect of strSubstring() is as if the two arguments were swapped; see example below.

Any argument value that is less than 0 or greater than value.length is treated as if it were 0 and value.length, respectively.

Any argument value that is NaN is treated as if it were 0.

const anyString = 'Nevware21';
// Displays 'N'
console.log(strSubstring(anyString, 0, 1));
console.log(strSubstring(anyString, 1, 0));

// Displays 'Nevwar'
console.log(strSubstring(anyString, 0, 6));

// Displays 'are21'
console.log(strSubstring(anyString, 4));

// Displays 'are'
console.log(strSubstring(anyString, 4, 7));

// Displays '21'
console.log(strSubstring(anyString, 7, 4));

// Displays 'Nevware'
console.log(strSubstring(anyString, 0, 7));

// Displays 'Nevware21'
console.log(strSubstring(anyString, 0, 10));
  • Parameters

    • value: string

      The string value to return the substring from.

    • indexStart: number

      The index of the first character to include in the returned substring.

    • OptionalindexEnd: number

      The index of the first character to exclude from the returned substring.

    Returns string

    A new string containing the specified part of the given string