Skip to content

Instantly share code, notes, and snippets.

@RockyMyx
Created May 13, 2013 06:00
Show Gist options
  • Save RockyMyx/5566428 to your computer and use it in GitHub Desktop.
Save RockyMyx/5566428 to your computer and use it in GitHub Desktop.
JavaScript: cut-string-api.js
//slice和substring接收的是起始位置和结束位置(不包括结束位置),而substr接收的则是起始位置和所要返回的字符串长度
var test = 'hello world';
test.slice(4, 7); //o w
test.substring(4, 7); //o w
test.substr(4, 7); //o world
//slice、substr使用负数作为参数表示从字符串尾部开始截取,substring则将负参数都直接转换为0
test.slice(-3); //rld
test.substring(-3); //hello world
test.substr(-3); //rld
test.slice(3, -4)); //lo w
test.substring(3, -4); //hel
//substr将第一个参数与字符串长度相加后的结果作为第一个参数
test.substr(3, -4); //空字符串
test.substr(-4, 3); //"orl"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment