/

HTML / CSS / JavaScript Tutorial

JavaScript String method: slice()

[this page | pdf | back links]

The slice() method (when applied to a JavaScript string) returns a new string formed by a part of the original string.

 

It has the following syntax with the following parameters:

 

string.slice(n1,n2)

 

Parameter

Required / Optional

Description

n1

Required

Position from where to begin extraction. 0 corresponds to the first character.

n2

Optional

(default is, in effect, string.length). Where to end extraction, so if omitted will select all characters from the n1’th position to the end of the 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.slice(1,4);';
document.getElementById("Result").innerHTML = y.slice(1,4);
</script>

</body>
</html>

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


NAVIGATION LINKS
Contents | Prev | Next | JavaScript String Variables


Desktop view | Switch to Mobile