JavaScript 字符串截取方法:substring、slice、substr、split
JavaScript 提供了多种方法来截取字符串,以下是常用的几种方法:
substring(start, end):从start位置开始截取,到end位置结束(不包括end位置),返回截取后的子字符串。
例如:
let str = 'hello world';
let newStr = str.substring(0, 5); // 截取从 0 到 5(不包括 5)的字符串
console.log(newStr); // 输出 'hello'
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'
substr(start, length):从start位置开始截取,截取length个字符,返回截取后的子字符串。
例如:
let str = 'hello world';
let newStr = str.substr(0, 5); // 截取从 0 开始的 5 个字符
console.log(newStr); // 输出 'hello'
split(separator, limit):将字符串按照指定的分隔符 (separator) 分成多个子字符串,并返回一个包含所有子字符串的数组。可选参数limit表示返回的子字符串数组的最大长度。
例如:
let str = 'hello,world';
let arr = str.split(','); // 以逗号为分隔符,分成两个子字符串
console.log(arr); // 输出 ['hello', 'world']
AI 优化版
原文地址:https://www.cveoy.top/t/topic/lWUh 著作权归作者所有。请勿转载和采集!