您的浏览器过于古老 & 陈旧。为了更好的访问体验, 请 升级你的浏览器
Ready 发布于2014年08月12日 06:22

原创 JavaScript String.substr() 函数详解

1795 次浏览 读完需要≈ 5 分钟

内容目录

substr()函数用于返回当前字符串中一个连续的片段。

该函数属于String对象,所有主流浏览器均支持该函数。虽然所有主流浏览器都实现了该函数,并且用法一致,但ECMAScript并没有对此函数进行标准化,因此无法确保该函数的用法是完全可靠的,因此不推荐使用本函数。请优先使用slice()substring()函数。

语法

stringObject.substr( startIndex [, length ] )

参数

参数 描述
startIndex Number类型指向字符串指定部分的开头的索引。
length 可选/Number类型返回的子字符串片段中包含的字符数。

substr()函数从stringObject的索引startIndex处开始复制,直到复制length个字符或字符串的结尾为止。

  • 如果startIndex为负,则将其视为stringObject.ength + startIndex
  • 如果length为负数或0,则不会复制任何字符,返回空字符串。如果省略了length参数,则一直复制到字符串的结尾。

返回值

substr()函数的返回值为String类型,返回当前字符串从索引startIndex开始的连续length个字符所组成的字符串。

示例&说明

var str = "Code Player";
document.writeln( str.substr(0, 4) ); // Code

document.writeln( str.substr(5, 6) ); // Player
// startIndex = 11+(-6) = 5 
document.writeln( str.substr(-6, 6) ); // Player
// 一直复制到字符串结尾
document.writeln( str.substr(5) ); // Player

document.writeln( str.substr(0, -1) ); // (空字符串)

运行代码

  • CodePlayer技术交流群1
  • CodePlayer技术交流群2

0 条评论

撰写评论

打开导航菜单