String substring() method in JavaScript

You can use the substring in JavaScript for extracting part or subset of a string. substring method returns extracted string in a new string.
substring works like the splice() method. It is similar to the slice() method. The only difference is substring() does not accept negative indexes.

Syntax:

str.substring(startPosition, endPosition);

Explanation:

Apply the substring method on str. You have to pass the following two arguments:
1) startPosition: index from which extracting is to be done.
2) endPosition: index to which end the extracting of string.
If this argument is not passed then the splice method extracts the rest of the string from startPosition.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>substring()</title>
  <script>
    var str = "HTML, CSS, JavaScript";
    var extractedString1 = str.substring(11, 21);
    document.write('Extracted string is: ', extractedString1);
    document.write("<br />")
    var extractedString2 = str.substring(5);
    document.write('Extracted string is: ', extractedString2);
  </script>
</head>
<body>
</body>
</html>

Output:

Extracted string is: JavaScript
Extracted string is: CSS, JavaScript

Additional Link:

String substr() method in JavaScript

Leave a Reply

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