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"]
js的字符串截取

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

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