JavaScript ,截取字符串多种方法(超详细)

在 JavaScript 中,你可以使用多种方法截取字符串,这取决于你的需求。以下是几种常见的截取字符串的方法:

1. substring() 方法

substring(startIndex, endIndex) 方法返回从 startIndexendIndex 之间的子字符串。endIndex 是可选的,如果省略,则截取到字符串的末尾。

const str = "Hello, World!"; 
const result = str.substring(0, 5); // 从索引 0 开始截取,到索引 5(不包括)结束 

console.log(result); // 输出 "Hello"

2. slice() 方法

slice(startIndex, endIndex) 方法也返回从 startIndexendIndex 之间的子字符串,endIndex 也是可选的。与 substring 不同的是,slice 允许使用负数索引,表示从字符串末尾开始计算。

const str = "Hello, World!";
const result = str.slice(0, 5); // 从索引 0 开始截取,到索引 5(不包括)结束 

console.log(result); // 输出 "Hello"

3. substr() 方法

substr(startIndex, length) 方法返回从 startIndex 开始,指定长度为 length 的子字符串。

const str = "Hello, World!"; 
const result = str.substr(0, 5); // 从索引 0 开始,截取长度为 5 

console.log(result); // 输出 "Hello"

4. charAt() 方法

charAt(index) 方法返回指定索引处的字符。

const str = "Hello, World!";
const result = str.charAt(0); // 获取索引 0 处的字符 

console.log(result); // 输出 "H"

5. substring()、slice()、substr() 的比较

  • substring:当 startIndex > endIndex 时,它会交换这两个值。
  • slice:支持负数索引,可以表示从字符串末尾开始计算的位置。
  • substr:第二个参数表示截取的长度。
 

javascriptCopy code

const str = "Hello, World!";
console.log(str.substring(7, 2)); // "ello",交换了 startIndex 和 endIndex 

console.log(str.slice(7, 2)); // "",返回空字符串

console.log(str.substr(7, 2)); // "Wo",从索引 7 开始截取长度为 2

根据你的需求,选择适当的方法来截取字符串。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值