/

HTML / CSS / JavaScript Tutorial

JavaScript String method: substring()

[this page | pdf | back links]

The substring() method (when applied to a JavaScript string) returns a substring defined by the start position and number of characters.

 

It has the following syntax with the following parameters:

 

string.substring(startposition, endposition)

 

Parameter

Required / Optional

Description

startposition

Required

Position from where to start returned string. First character is at position 0.

endposition

Optional

(default is string.length). Position up to (but not including) where characters are returned from. If omitted then returns rest of string. If before startposition then the two are treated as if they were reversed.

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse: collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>

<script>
var y = "abcde";
document.getElementById("Example").innerHTML =
  'var y = "' + y + '";<br>' +
  'var x = y.substring(1, 3);';
document.getElementById("Result").innerHTML =
  y.substring(1, 3);
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodStringSubstring() {
  var z = "abc"; return !!z.substring;
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript String Variables


Desktop view | Switch to Mobile