'substr()' 是 JavaScript 中用于从字符串中提取指定位置子字符串的方法。它接受两个参数:起始索引和要提取的字符数。

  • 起始索引 指示要提取子字符串的起始位置。
  • 要提取的字符数 指示要提取的字符数量。

例如,以下代码将从字符串 'Hello world' 中提取从索引 6 开始的 5 个字符:

const str = 'Hello world';
const subStr = str.substr(6, 5); // subStr 将包含 'world'

注意:

  • 如果起始索引超出字符串长度,则返回一个空字符串。
  • 如果要提取的字符数超过了剩余的字符数量,则返回从起始索引开始到字符串末尾的子字符串。

示例:

const str = 'Hello world';

// 从索引 0 开始提取 5 个字符
const subStr1 = str.substr(0, 5); // subStr1 将包含 'Hello'

// 从索引 6 开始提取 5 个字符
const subStr2 = str.substr(6, 5); // subStr2 将包含 'world'

// 从索引 12 开始提取 5 个字符(超出字符串长度)
const subStr3 = str.substr(12, 5); // subStr3 将包含 ''

// 从索引 6 开始提取 10 个字符(超过剩余字符数量)
const subStr4 = str.substr(6, 10); // subStr4 将包含 'world'
JavaScript substr() 方法详解:提取字符串子串

原文地址: https://www.cveoy.top/t/topic/pjCz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录