美文网首页@IT·互联网程序员让前端飞
JavaScript中substring()、substr()、

JavaScript中substring()、substr()、

作者: 07120665a058 | 来源:发表于2017-04-18 21:33 被阅读660次

区别

  • substring(start,end)返回指定下标间的字符,下标必须为正整数
  • substr(start,length)返回从指定下标开始的长度为length的字符,可以为负数
  • slice(start,end)返回指定下标间的字符,可以为负数

注意点

  • 不写结束下标默认到末尾
  • 如果start=end则返回空字符串
  • 如果任一参数小于0,则被当做0
  • 如果任一参数大于字符串的长度,则被当做字符串的长度

demo

var stringValue = "hello world";

console.log(stringValue.slice(3));          //”lo world”
console.log(stringValue.substring(3));      //”lo world”
console.log(stringValue.substr(3));        //”lo world”

console.log(stringValue.slice(3,7));         //”lo w”
console.log(stringValue.substring(3,7));    //”lo w”
console.log(stringValue.substr(3,7));       //”lo worl”

console.log(stringValue.slice(-3));         //"rld" 从后往前数3个开始
console.log(stringValue.substring(-3));     //"hello world" 为负,默认从0开始
console.log(stringValue.substr(-3));        //"rld"

console.log(stringValue.slice(3,-4));       //”lo w” 下标从3开始到-4(从后往前数4个)
console.log(stringValue.substring(3,-4));   //”hel” 
console.log(stringValue.substr(3,-4));      //”” 长度为负,默认不显示

参考文章推荐
String.prototype.substring()
javascript中substring()、substr()、slice()的区别

相关文章

网友评论

    本文标题:JavaScript中substring()、substr()、

    本文链接:https://www.haomeiwen.com/subject/vautzttx.html