了解下中字符串的函数有哪些:slice、substring、substr

  了解下中截取字符串的函数有哪些:slice()、substring()、substr()。

  在JS中,slice()、substring()、substr()都有截取字符串的作用

  1、substring()

  substring()方法返回一个索引和另一个索引之间的字符串js根据斜杠截取字符串,语法如下:

  str.substring(indexStart, [indexEnd])

  下面有六点需要注意:

  以下是一些示例代码:

  

var str = 'abcdefghij';
console.log('(1, 2): '   + str.substring(1, 2));   // '(1, 2): b'
console.log('(1, 1): '   + str.substring(1, 1));   // '(1, 1): '
console.log('(-3, 2): '  + str.substring(-3, 2));  // '(-3, 2): ab'
console.log('(-3): '     + str.substring(-3));     // '(-3): abcdefghij'
console.log('(1): '      + str.substring(1));      // '(1): bcdefghij'
console.log('(-20, 2): ' + str.substring(-20, 2)); // '(-20, 2): ab'
console.log('(2, 20): '  + str.substring(2, 20));  // '(2, 20): cdefghij'
console.log('(20, 2): '  + str.substring(20, 2));  // '(20, 2): cdefghij'

  2、substr()

  substr()方法返回从指定位置开始的字符串中指定字符数的字符js根据斜杠截取字符串,语法如下:

  str.substr(start, [length])

  下面有四点需要注意:

  以下是一些示例代码:

  

var str = 'abcdefghij';
console.log('(1, 2): '   + str.substr(1, 2));   // '(1, 2): bc'
console.log('(-3, 2): '  + str.substr(-3, 2));  // '(-3, 2): hi'
console.log('(-3): '     + str.substr(-3));     // '(-3): hij'
console.log('(1): '      + str.substr(1));      // '(1): bcdefghij'
console.log('(-20, 2): ' + str.substr(-20, 2)); // '(-20, 2): ab'
console.log('(20, 2): '  + str.substr(20, 2));  // '(20, 2): '

  需要注意的是,Microsoft的JScript不支持起始索引的负值。如果要使用此功能,可以使用以下兼容性代码来解决此错误:

  

// only run when the substr() function is broken
if ('ab'.substr(-1) != 'b') {
  
  String.prototype.substr = function(substr) {
    return function(start, length) {
      // call the original method
      return substr.call(this,
       // did we get a negative start, calculate how much it is from the beginning of the string
        // adjust the start parameter for negative value
        start  "zil"
console.log(text.substr(2,3)); // => "zil"

  4、slice()

  slice()方法返回一个索引和另一个索引之间的字符串,语法如下:

  

str.slice(beginIndex[, endIndex])

  下面有三点需要注意:

  以下是一些示例代码:

  

var str = 'abcdefghij';
console.log('(1, 2): '   + str.slice(1, 2));   // '(1, 2): b'
console.log('(-3, 2): '  + str.slice(-3, 2));  // '(-3, 2): '
console.log('(-3, 9): '  + str.slice(-3, 9));  // '(-3, 9): hi'
console.log('(-3): '     + str.slice(-3));     // '(-3): hij'
console.log('(-3,-1): ' + str.slice(-3,-1));     // '(-3,-1): hi'
console.log('(0,-1): '  + str.slice(0,-1));     // '(0,-1): abcdefghi'
console.log('(1): '      + str.slice(1));      // '(1): bcdefghij'
console.log('(-20, 2): ' + str.slice(-20, 2)); // '(-20, 2): ab'
console.log('(20): '     + str.slice(20));  // '(20): '
console.log('(20, 2): '  + str.slice(20, 2));  // '(20, 2): '

TAGS:字符串函数 js截取字符串 索引 slice js根据斜杠截取字符串 substring jq截取斜杠前面的文字 php截取最后一个斜杠
!如链接失效请在下方留言。本站所有资源均来源于网络,版权属于原作者!仅供学习参考,本站不对您的使用负任何责任。如果有侵权之处请第一时间联系我们删除,敬请谅解!