JavaScript slice() method
JavaScript String Object
Definition and Usage
The slice() method extracts a part of a string and returns the extracted part in a new string.
Otherwise it returns -1.
Syntax
| stringObject.slice(begin,end) |
| Parameter |
Description |
| begin |
Required. Where to begin the extraction. Must be a
number. Starts at 0 |
| end |
Optional. Where to end the extraction. If omitted, slice()
selects all characters from the begin position to the end of the string |
Tips and Notes
Tip: You can use a negative numbers to select from the end of a string.
Example
Example
Extract different parts of a string:
<script type="text/javascript">
var str="Hello happy world!";
// extract all characters, start at position 0:
document.write(str.slice(0)+"<br />");
// extract all characters, start at position 6:
document.write(str.slice(6)+"<br />");
// extract from the end of the string, and to position -6:
document.write(str.slice(-6)+"<br />");
// extract only the first character:
document.write(str.slice(0,1)+"<br />");
// extract the characters from position 6 to position 11:
document.write(str.slice(6,11)+"<br />");
</script>
|
The output of the code above will be:
Hello happy world!
happy world!
world!
H
happy
|
Try it yourself »
|
JavaScript String Object
|