JS截取字符串:slice(),substring()和substr()

var string='abcdefg'

1、slice()

string.slice(startLocation [, endLocation])

ps1:2个参数可以为负数,若参数值为负数,则将该值加上字符串长度后转为正值(可以理解为从右开始)

ps2:endLocation缺省时,默认为末尾位置

string.slice(1,3)   //return 'bc'

string.slice(1,-1)   //return 'bcdef'

2、substring()

string.substring(startLocation [, endLocation])

ps1:参数为负数时,转换为0。

ps2:两个参数中,取较小值作为开始位置,截取出来的字符串的长度为较大值与较小值之间的差.

ps3:endLocation缺省时,默认为末尾位置

string.substring(1,3) //return 'bc'

string.substring(1,-1) //return 'a'

3、substr()

string.substr(start [, length ])

ps1:若参数值为负数,则将该值加上字符串长度后转为正值(可以理解为从右开始)

ps2:length为负数时转为0,返回空字符串。

ps2:length缺省时,默认到末尾

string.substr(1,3)    //return 'bcd'

string.substr(1,-1)    //return ''

原文地址:https://www.cnblogs.com/xiexiaobao/p/5305732.html