Javascript String substring()

The substring() method returns a specified part of the string between start and end indexes.

Example

const message = "JavaScript is fun.";

// get the substring starting from index 0 to 10 let result = message.substring(0, 10);
console.log(result); // Output: JavaScript

substring() Syntax

The syntax of the substring() method is:

str.substring(indexStart, indexEnd)

Here, str is a string.


substring() Parameters

The substring() method takes in:

  • indexStart - The index of the first character to start including in the returned substring.
  • indexEnd (optional) - The index before which to stop extraction. (Exclusive) If omitted, it extracts till the end of the string.

Notes:

  • Any argument value < 0 is treated as 0.
  • Any argument value > str.length is treated as str.length.
  • Any NaN argument value is treated as 0.
  • If indexStart is greater than indexEnd, the two arguments are swapped, i.e. str.substring(a, b) will be str.substring(b, a).

substring() Return Value

  • Returns a new string containing the specified part of the given string.

Note: substring() does not change the original string.


Example 1: Using substring

let string = "Programiz JavaScript Tutorials";

// first character substr1 = string.substring(0, 1);
console.log(substr1); // P
// if start > end, they are swapped substr2 = string.substring(1, 0);
console.log(substr2); // P // From 11th to last character substr3 = string.substring(10); console.log(substr3); // JavaScript Tutorials // the extreme values are 0 and str.length
// same as string.substring(0) substr4 = string.substring(-44, 90);
console.log(substr4); // Programiz JavaScript Tutorials
// indexEnd is exclusive substr5 = string.substring(0, string.length - 1);
console.log(substr5); // Programiz JavaScript Tutorial

Output

P
P
JavaScript Tutorials
Programiz JavaScript Tutorials
Programiz JavaScript Tutorial

Example 2: Replacing a substring within a string

// Replaces old characters with new characters in a string
function replaceString(oldChars, newChars, string) {
  for (let i = 0; i < string.length; ++i) {
if (string.substring(i, i + oldChars.length) == oldChars) { string = string.substring(0, i) + newChars + string.substring(i + oldChars.length, string.length);
} } return string; } const string = "Java Tutorials"; let newString = replaceString("Java", "JavaScript", string); console.log(newString); // JavaScript Tutorials

Output

JavaScript Tutorials

Recommended Reading: JavaScript String slice()

Did you find this article helpful?