String substr() method in JavaScript

You can use the substr() method in JavaScript to extract part or section of the string starting at a specified location to the length of characters to extract. substr method returns extracted string in a new string.
It is similar to the slice() method. The only difference is that substr() method accepts the second argument as the length of characters to extract.

Syntax:

str.substr(startPosition, length);

Explanation:

Apply substr() method on str. You have to pass the following two arguments:
1) startPosition: index from which extracting is to be done.
2) endPosition: length of characters to extract from startPosition.
If this argument is not passed then the substr() method in JavaScript 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>substr()</title>
  <script>
    var str = "HTML, CSS, JavaScript";
    var extractedString1 = str.substr(11, 15);
    document.write('Extracted string is: ', extractedString1);
    document.write("<br />");
    var extractedString2 = str.substr(5);
    document.write('Extracted string is: ', extractedString2);
  </script>
</head>
<body>
</body>
</html>

Output:

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

If a negative parameter is passed as startPosition then it starts counting from the end of the string.

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>substr()</title>
  <script>
    var str = "HTML, CSS, JavaScript";
    var extractedString = str.substr(-15, 3);
    document.write('Extracted String is: ', extractedString); 
  </script>
</head>
<body>
</body>
</html>

Output:

Extracted String is: CSS

Leave a Reply