Extracting String Parts: Substr() Method

The last of three methods for extracting a part of a string is the substr(start, length), which also is similar to slice(). The difference here is that the second parameter specifies the length of the extracted part. This means that the script will return 6 characters starting from the 7th location:

   var str = "Apple, Banana, Kiwi";
   var res = str.substr(7,6);

HTML file: Displayed by browser:
<body>
<p>The substr() method extract a part of a string and returns the extracted parts in a new string:</p>
<p id="demo"></p>
<script>
    var str = "Apple, Banana, Kiwi";
    document.getElementById("demo").innerHTML = str.substr(7,6);
</script>
</body>

The substr() method extract a part of a string and returns the extracted parts in a new string:

If the first parameter is negative, the position counts from the end of the string. The second parameter can not be negative, because it defines the length. If you omit the second parameter, substr() will slice out the rest of the string:
     var res = str.substr(7);    The result of res will be Banana, Kiwi

BackTable of ContentsNext