JavaScript substring, 方法

Definition and Usage

定义与用法

The substring() method extracts the characters in a string between two specified indices.

substring()方法用于取出字符串中特定位置间的字符

Syntax

语法

stringObject.substring(start,stop)
Parameter

参数

Description

注释

start

开始位置

Required. Where to start the extraction. Must be a numeric value

必选项。开始选取的位置。必须为数字。

stop

停止

Optional. Where to stop the extraction. Must be a numeric value

可选项。停止选取的位置。必须为数字。


Tips and Notes

注意

Note: To extract characters from the end of the string, use a negative start number.

注意:要从字符的尾部开始取字符,用负数做为起始字符。

Note: The start index starts at 0.

注意:第一个字符的位置为0

Note: If the stop parameter is omitted, this method extracts to the end of the string.

注意:如果为指定结束位置,默认将选取到字符串结束。


Example

实例

In this example we will use substring() to extract some characters from a string:

在本例中,我们将演示substring()从字符串中选取一些字符:

<script type="text/javascript">
var str="Hello world!"
document.write(str.substring(3))
</script>

The output of the code above will be:

输出结果为:

lo world!