温馨提示×

js substring的用法有哪些

小亿
100
2023-08-01 11:39:49
栏目: 编程语言

JavaScript中的substring()函数用于提取字符串中的一部分。它有两种形式的用法:

  1. 使用两个参数:substring(startIndex, endIndex)
  • startIndex:要提取的子字符串的起始位置,包括该位置的字符。

  • endIndex(可选):要提取的子字符串的结束位置,不包括该位置的字符。如果省略该参数,则提取到字符串的末尾。

  1. 使用一个参数:substring(startIndex)
  • startIndex:要提取的子字符串的起始位置,包括该位置的字符。此时,子字符串将从startIndex开始一直提取到字符串的末尾。

以下是一些具体的用法示例:

let str = "JavaScript Substring Example";
// 提取字符串的前5个字符
let substr1 = str.substring(0, 5);
console.log(substr1); // 输出:JavaS
// 提取从索引位置6开始到索引位置16的字符
let substr2 = str.substring(6, 17);
console.log(substr2); // 输出:cript Substri
// 提取从索引位置12开始到字符串末尾的字符
let substr3 = str.substring(12);
console.log(substr3); // 输出:Substring Example

需要注意的是,如果startIndex大于endIndex,则substring()函数会自动交换这两个参数的值,保证startIndex始终小于等于endIndex。如果任一参数是负数或大于字符串的长度,则会被视为0或字符串长度。

0