Home >>JavaScript String Methods >JavaScript String substring() Method

JavaScript String substring() Method

JavaScript String substring() Method

JavaScript substring() method is used to extract the characters from a given input string between two specified indexes and return the new substring as a result. It does not change the original string.

Syntax:

string.substring(start, end)

Parameter Values

Parameter Description
start This is a required parameter. It defines the position where to start the extraction.
end This is an optional parameter. It defines the position where to end the extraction.

Browser Support

Method Chrome Edge Firefox Safari Opera
substring() Yes Yes Yes Yes Yes

Here is an example of substring() method:

<html>
<body>
<p>Click the button to see the Output.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
  var str = "Welcome to PHPTPOINT!!";
  var res = str.substring(0, 7);
  document.getElementById("demo").innerHTML = res;
}
</script>
</body>
</html>
Output:

Click the button to see the Output.

 

Example 2:

<html>
<body>
<p>Click the button to see the Output.</p>
<button onclick="myFunction1()">Try it</button>
<p id="demo1"></p>
<script>
function myFunction1() {
  var str = "Welcome to PHPTPOINT!!";
  var res = str.substring(str.length - 2, str.length-11);
  document.getElementById("demo1").innerHTML = res;
}
</script>
</body>
</html>
Output:

Click the button to see the Output.