js 前端字符串截取
时间: 2023-08-26 07:13:43 浏览: 122
在前端中,可以使用以下几种方法来截取字符串:
1. `substring(startIndex, endIndex)`: 使用指定的起始索引和结束索引截取字符串。起始索引是要截取的子字符串的第一个字符的索引,而结束索引是要截取的子字符串的最后一个字符的下一个索引。示例:`var str = "Hello World"; var result = str.substring(0, 5); // 输出 "Hello"`
2. `slice(startIndex, endIndex)`: 使用指定的起始索引和结束索引截取字符串。与`substring()`方法不同的是,`slice()`方法允许负数索引,负数索引表示从字符串末尾开始计算。示例:`var str = "Hello World"; var result = str.slice(0, 5); // 输出 "Hello"`
3. `substr(startIndex, length)`: 使用指定的起始索引和长度截取字符串。起始索引是要截取的子字符串的第一个字符的索引,而长度是要截取的子字符串的长度。示例:`var str = "Hello World"; var result = str.substr(0, 5); // 输出 "Hello"`
4. `substring()`、`slice()`和`substr()`方法都可以省略参数。如果省略了第二个参数,则表示截取到字符串的末尾。示例:`var str = "Hello World"; var result = str.substring(6); // 输出 "World"`
这些方法都返回截取后的子字符串,不会修改原始字符串。请根据自己的需求选择适合的方法。
阅读全文
相关推荐















