2,slice 方法, substring 方法, substr 方法
slice 方法:
第一个参数指定子字符串开始位置, 第二个参数表示子字符串最后一个字符后面的位置,
如果只有一个参数 n, 返回的是从 n-1 位置开始到字符串结尾的字符串
如果两个参数都是整数, 同为正或同为负, 第二个参数必须必第一个参数大, 否则返回的是空字符串
如果第一个参数是负数, 第二个参数是非负正数的时候, 均返回空字符串
如果第一个参数是 0, 第二个参数是正数 n, 返回的是从 0 位置开始到 n-1 位置结束的字符串
如果第一个参数是 0 正数 n, 第二个参数是负数 m, 返回的是从 0 或 n 开始到从右边数第 m-1 位置结束的字符串
如果两个参数均为负数 m,n,m<n 的时候, 返回的是从右边第 | n|+1 位置开始到第 | m | 位置结束的字符串
- var str = 'hello world';
- console.log(str.slice(3));// lo world
- console.log(str.slice(-1, -3));// 空字符串
- console.log(str.slice(3, 1));// 空字符串
- console.log(str.slice(-1, 0));// 空字符串
- console.log(str.slice(-1, 2));// 空字符串
- console.log(str.slice(0, 2));// he
- console.log(str.slice(0, -1));// hello worl
- console.log(str.slice(1, -3));// ello wo
- console.log(str.slice(-3, -1));// rl
- console.log(str);// hello world
substring 方法: 第一个参数指定子字符串开始位置, 第二个参数表示子字符串最后一个字符后面的位置, 如果存在第二个参数, 第二个参数为负数时, 返回空字符串
substr 方法: 第一个参数指定子字符串开始位置, 第二个参数表示返回的字符个数
这三个方法都会返回被操作字符串的一个子字符串, 都接收一或两个参数
如果没有给这些方法传递第二个参数, 则将字符串的长度作为结束位置. 这些方法也不会修改字符串本身, 只是返回一个基本类型的字符串值
例如:
- var str = 'hello world';
- console.log(str.substring(0, 2));// he
- console.log(str.substring(0, -2));// 空字符串
- console.log(str.substring(3, 1));// el
- console.log(str.substring(3));// lo world
来源: http://www.qdfuns.com/note/40690/fa233231f7fdc2d9298bb29ddf7fe57a.html