JavaScript 提供了多种方法来截取字符串,以下是常用的几种方法:

  1. substring(start, end):从 start 位置开始截取,到 end 位置结束(不包括 end 位置),返回截取后的子字符串。

例如:

let str = 'hello world';
let newStr = str.substring(0, 5); // 截取从 0 到 5(不包括 5)的字符串
console.log(newStr); // 输出 'hello'
  1. slice(start, end):与 substring 方法类似,从 start 位置开始截取,到 end 位置结束(不包括 end 位置),返回截取后的子字符串。不同的是,slice 方法可以接受负数参数,表示从字符串末尾开始计算位置。

例如:

let str = 'hello world';
let newStr = str.slice(0, 5); // 截取从 0 到 5(不包括 5)的字符串
console.log(newStr); // 输出 'hello'

let newStr2 = str.slice(-5); // 截取最后 5 个字符
console.log(newStr2); // 输出 'world'
  1. substr(start, length):从 start 位置开始截取,截取 length 个字符,返回截取后的子字符串。

例如:

let str = 'hello world';
let newStr = str.substr(0, 5); // 截取从 0 开始的 5 个字符
console.log(newStr); // 输出 'hello'
  1. split(separator, limit):将字符串按照指定的分隔符 (separator) 分成多个子字符串,并返回一个包含所有子字符串的数组。可选参数 limit 表示返回的子字符串数组的最大长度。

例如:

let str = 'hello,world';
let arr = str.split(','); // 以逗号为分隔符,分成两个子字符串
console.log(arr); // 输出 ['hello', 'world']
JavaScript 字符串截取方法:substring、slice、substr、split