当前位置: 首页 > 网络学院 > 客户端脚本教程 > JavaScript > JavaScript slice() 方法
The slice() method extracts a part of a string and returns the extracted part in a new string.
slice()方法从一个字符串选取一部分字符,并将它们返回成一个新的字符串
stringObject.slice(start,end) |
Parameter 参数 | Description 注释 |
---|---|
start 起始位置 | Required. Specify where to start the selection. Must be a number 必选项。指定从哪里开始选取,必须为数字 |
end 终止位置 | Optional. Specify where to end the selection. Must be a number 可选项。指定选取结束的位置,必须为数字 |
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.
注意:如果没有指定结束的位置,slice()将选取从指定起始位置开始到字符串结束的所有字符
In this example we will extract all characters from a string, starting at position 6:
在本例中,我们将选取字符串中第6个字符以后的所有字符:
<script type="text/javascript"> var str="Hello happy world!" </script> |
The output of the code above will be:
输出结果为:
happy world! |
In this example we will extract all the characters from position 6 to position 11:
在本例中,我们将从字符串中选取第6个字符到第11个字符间的字符:
<script type="text/javascript"> var str="Hello happy world!" </script> |
The output of the code above will be:
输出结果为:
happy |
slice()
How to use slice() to extract characters from a string.
如何用slice()从字符串中选取字符