/

HTML / CSS / JavaScript Tutorial

JavaScript String method: substr()

[this page | pdf | back links]

The substr() 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.substr(startposition,n)

 

Parameter

Required / Optional

Description

startposition

Required

Position from where to start returned string. First character is at position 0. If startposition is positive and greater than or equal to string.length then returns an empty string. If startposition is negative then indicates number of characters before end from which to start (and if it is negative and larger in absolute value than the length of the string then a startposition of zero is used.

n

Optional

(default is string.length). Number of characters to return, if omitted returns whole of rest of string

 

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.substr(1, 3);';
document.getElementById("Result").innerHTML =
  y.substr(1, 3);
</script>

</body>
</html>

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


NAVIGATION LINKS
Contents | Prev | Next | JavaScript String Variables


Desktop view | Switch to Mobile