当前位置:   article > 正文

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

js字符串截取

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

1. substring() 方法

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

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

2. slice() 方法

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

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

3. substr() 方法

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

  1. const str = "Hello, World!";
  2. const result = str.substr(0, 5); // 从索引 0 开始,截取长度为 5
  3. console.log(result); // 输出 "Hello"

4. charAt() 方法

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

  1. const str = "Hello, World!";
  2. const result = str.charAt(0); // 获取索引 0 处的字符
  3. console.log(result); // 输出 "H"

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

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

javascriptCopy code

  1. const str = "Hello, World!";
  2. console.log(str.substring(7, 2)); // "ello",交换了 startIndex 和 endIndex
  3. console.log(str.slice(7, 2)); // "",返回空字符串
  4. console.log(str.substr(7, 2)); // "Wo",从索引 7 开始截取长度为 2

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/883121
推荐阅读
相关标签
  

闽ICP备14008679号