ES6字符串

ES6 新增了很多方法如:includes(),startsWith(),endsWith(),repeat(),padStart(),padEnd(),trimStart(),trimEnd(),at()

 includes():返回布尔值,判断是否找到参数字符串

let string = "hello,words,hi";

console.log(string.includes("hello")); // true

startsWith():返回布尔值,判断参数字符串是否在原字符串的头部

let string = "hello,words,hi";

console.log(string.startsWith("hello")); // true

endsWith():返回布尔值,判断参数字符串是否在原字符串的尾部

let string = "hello,words,hi";

console.log(string.endsWith("hello")); // false

console.log(string.endsWith("hi")); // true

repeat():返回新的字符串,表示将字符串重复指定次数返回 

console.log("hello,".repeat(3));//"hello,hello,hello"

如果参数是小数,向下取整

console.log("hello,".repeat(3.3));//"hello,hello,hello"

如果参数是 0 至 -1 之间的小数或者NaN,会进行取整运算,等同于 repeat 零次

console.log("hello,".repeat((-0.1));      console.log("hello,".repeat((NaN));

如果参数是负数或者 Infinity ,会报错:

console.log("hello,".repeat((-1));  // RangeError: Invalid count value

console.log("hello,".repeat((Infinity ));  // RangeError: Invalid count value

padStart():返回新的字符串,表示用参数字符串从头部(左侧)补全原字符串 

 console.log("a".padStart(3,"b"));//"bba"

3是表示返回的字符串长度

padEnd():返回新的字符串,表示用参数字符串从尾部(右侧)补全原字符串

  console.log("a".padEnd(3,"b"));//"abb"

如果指定的长度小于或者等于原字符串的长度,则返回原字符串: 

console.log("hi".padStart(2,"b"));//"hi"

如果原字符串加上补全字符串长度大于指定长度,则截去超出位数的补全字符串: 

 console.log("hi".padEnd(6,",hhha"));//"hi,hhh"

常用于补全位数

trim():消除字符串空格

trimStart(): 消除字符串头部的空格

trimEnd(): 消除字符串尾部的空格

console.log('  hello'.trimStart());//hello

console.log('  hello   '.trim());//hello

console.log('hello    '.trimEnd());//hello

at():返回参数指定位置的字符,支持负索引

 console.log('hello'.at(1));//e

 console.log('hello'.at(-1));//o

 console.log('hello'.at(10));//undefined

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值