JavaScript slice() method
Complete String Object Reference
Definition and Usage
The slice() method extracts a part of a string and returns the extracted part
in a new string.
Syntax
stringObject.slice(start,end)
|
Parameter |
Description |
start |
Required. Specify where to start the selection. Must be a
number. Starts at 0 |
end |
Optional. Specify where to end the selection. Must be a
number |
Tips and Notes
Tip: You can use negative index numbers to select from the end of the
string.
Note: If end is not specified, slice() selects all characters from the
specified start position and to the end of the string.
Example 1
In this example we will extract all characters from a string, starting at
position 0:
<script type="text/javascript">
var str="Hello happy world!";
document.write(str.slice(0));
</script>
|
The output of the code above will be:
Example 2
In this example we will extract all characters from a string, starting at
position 6:
<script type="text/javascript">
var str="Hello happy world!";
document.write(str.slice(6));
</script>
|
The output of the code above will be:
Example 3
In this example we will extract only the first character from a string:
<script type="text/javascript">
var str="Hello happy world!";
document.write(str.slice(0,1));
</script>
|
The output of the code above will be:
Example 4
In this example we will extract all the characters from position 6 to
position 11:
<script type="text/javascript">
var str="Hello happy world!";
document.write(str.slice(6,11));
</script>
|
The output of the code above will be:
Try-It-Yourself Demos
slice()
How to use slice() to extract characters from a string.
Complete String Object Reference
|
|
|
See why there are 20,000+ Ektron integrations worldwide.
Request an INSTANT DEMO or download a FREE TRIAL today. |
|
|
|