了解ES6-字符串
ES6新增了子串的识别方法
- includes(“str”):判断是否找到参数字符串,返回类型是布尔值。
- startsWith(“str”):判断参数字符串是否在原字符串的头部,返回类型是布尔值。
- endsWith(“str”):判断参数字符串是否在原字符串的尾部,返回类型是布尔值。
示例代码
var str = "apple,banana,orange";
str.includes("banana"); // true,判断该字符串是否包含
str.startsWith("apple"); // true,判断该字符串是否出现在头部
str.startsWith("banana",6) // true,startsWith("banana",6) 里面的参数6为查询的起始位置
str.endsWith("apple"); // false,判断该字符串是否出现在尾部
运行结果如下图
注意点
这三个方法只返回布尔值,如果需要知道子串的位置,还是得用 indexOf 和 lastIndexOf 。
这三个方法如果传入了正则表达式而不是字符串,会抛出错误。而 indexOf 和 lastIndexOf 这两个方法,
它们会将正则表达式转换为字符串并搜索它。
字符串重复
repeat():返回新的字符串,表示将字符串重复指定次数返回。
repeat()参数有小数,则向下取整,
如果repeat()参数是 0 至 -1 之间的小数,会进行取整运算,那么repeat(0)参数等于0次
如果repeat()参数是 NaN,那么repeat(0)参数等于0次
如果repeat()参数是负数或Infinity的话会报错
如果repeat(“str”)传入的参数是字符串,则会先将字符串转化为数字
示例代码
console.log("Hello,".repeat(2)); // "Hello,Hello,"repeat(2)里面是2所有会返回两遍Hello
console.log("Hello,".repeat(3.2)); // "Hello,Hello,Hello,"
console.log("Hello,".repeat(-0.5)); // ""
console.log("Hello,".repeat(NaN)); // ""
console.log("Hello,".repeat(-1));
console.log("Hello,".repeat(Infinity));
console.log("Hello,".repeat("hh")); // ""
console.log("Hello,".repeat("2")); // "Hello,Hello,"