JavaScript String substr() 方法用于提取字符串的一部分(字符串的一部分),从指定索引开始并扩展给定数量的字符。
以下是有关 substr() 方法的一些其他要点,如下所示 -
- 如果起始索引值大于字符串长度,则返回空字符串。
- 如果 start index 值小于零(或负数),则从字符串的末尾开始计数。
- 如果 start index 参数被省略或未定义,则将其视为 0。
- 如果 length 参数值小于零(或负数),则返回空字符串。
JavaScript String substr() 方法是已弃用的方法。不再推荐使用此功能。它可能已从相关的 Web 标准中删除。
语法
以下是 JavaScript String substr() 方法的语法 -
substr(start, length)
参数
此方法接受两个名为 'start' 和 'length' 的参数,如下所述 -
- start − 要包含在返回的子字符串中的第一个字符的索引(位置)。
- length (可选) − 要提取的字符数。
返回值
此方法返回一个新字符串,其中包含给定字符串的部分(或部分)。
示例 1
如果省略 length 参数,它将从指定的起始位置开始提取并延伸到字符串的末尾。
在下面的程序中,我们使用 JavaScript String substr() 方法从给定的字符串 “QikepuCom” 中提取字符串的一部分,从指定的起始位置 3 开始。
<html> <head> <title>JavaScript String substr() Method</title> </head> <body> <script> const str = "
QikepuCom"; document.write("Given string: ", str); const start = 3; document.write("<br>The start position: ", start); // 使用substr()方法 var new_str = str.substr(start); document.write("<br>The new string: ", new_str); </script> </body> </html>
输出
上面的程序返回一个新字符串 “orialsPoint”。
Given string: QikepuCom
The start position: 3
The new string: epuCom
The start position: 3
The new string: epuCom
示例 2
如果我们将 start 和 length 参数都传递给此方法,它将从指定的开始位置开始提取字符,并继续提取给定长度的字符。
以下是 JavaScript String substr() 方法的另一个示例。我们使用此方法从给定的字符串 “Hello World” 中检索字符串的一部分,从指定的起始位置 4 开始,一直延伸到给定的字符长度 8。
<html>
<head>
<title>JavaScript String substr() Method</title>
</head>
<body>
<script>
const str = "Hello World";
document.write("Given string: ", str);
const start = 4;
const length = 8;
document.write("<br>The start position: ", start);
document.write("<br>The length of the charcters: ", length);
//using the substr() method
var new_str = str.substr(start, length);
document.write("<br>The new string: ", new_str);
</script>
</body>
</html>
输出
执行上述程序后,它将返回一个新字符串作为 −
Given string: Hello World
The start position: 4
The length of the charcters: 8
The new string: o World
The start position: 4
The length of the charcters: 8
The new string: o World
示例 3
如果 start 参数值超过给定字符串的长度,则返回空字符串。
在此示例中,我们使用 JavaScript String substr() 方法从给定的字符串 “JavaScript” 中提取字符串的一部分,从指定的起始位置 15 开始。
<html>
<head>
<title>JavaScript String substr() Method</title>
</head>
<body>
<script>
const str = "JavaScript";
document.write("Given string: ", str);
const start = 15;
document.write("<br>The start position: ", start);
//using the substr() method
var new_str = str.substr(start);
document.write("<br>The new string: ", new_str);
</script>
</body>
</html>
输出
执行上述程序后,它将返回一个空字符串。
Given string: JavaScript
The start position: 15
The new string:
The start position: 15
The new string: