温馨提示×

js substring方法的作用是什么

js
小亿
109
2023-07-31 11:04:03
栏目: 编程语言

JavaScript的substring()方法用于从字符串中提取指定范围的子字符串,并返回提取的子字符串。

它有两种使用方式:

  1. substring(startIndex, endIndex):提取从startIndex到endIndex之间的字符,不包括endIndex位置的字符。如果省略endIndex,则提取从startIndex到字符串末尾的所有字符。

例如:

let str = "Hello, World!";
let subStr = str.substring(0, 5);
console.log(subStr); // 输出 "Hello"
  1. substring(startIndex):提取从startIndex到字符串末尾的所有字符。

例如:

let str = "Hello, World!";
let subStr = str.substring(7);
console.log(subStr); // 输出 "World!"

需要注意的是,如果startIndex大于endIndex,则substring()方法会自动交换这两个参数的位置。

此外,substring()方法不会修改原始字符串,而是返回一个新的字符串。

0