判断是否包含

ES6提供了三个方法用于判断字符串是否包含。

  • includes(str,[index])

    判断指定位置开始,字符串是否包含指定字符串

  • startsWith(str,[index])

    字符串的索引值开始是否以另一个字符串开头

  • endsWith(str,[index])

    字符串的索引值开始是否以另一个字符串结尾

三个方法的使用方法基本保持一致。

  • 区分大小写
  • 第一个参数为待搜索的字符串
  • 第二个参数表示开始的索引位置,默认为0
  • 结果返回布尔值
1
2
3
4
5
let str = "xiaokangboke";
console.log(str.includes("o")); //true
console.log(str.includes("o", 3)); //true
// 区分大小写
console.log(str.includes("O", 3)); //false

如果想要不区分大小写可以将字符串全部转化为大/小写,然后在判断是否包含。示例:

1
2
3
4
5
6
7
8
let str = "xiaokangboke";
// 基于includes实现不区分大小写的判断
function myIncludes(str, searchStr, index = 0) {
str = str.toLowerCase();
searchStr = searchStr.toLowerCase();
return str.includes(searchStr, index);
}
console.log(myIncludes(str, "x")); //true

重复字符串

repeat(number)方法用于将原字符串重复n次,返回一个新的字符串。例如:

1
2
3
4
5
let str = "abc";
console.log(str.repeat(3)); // abcabcabc
console.log(str.repeat(0)); // '' 空字符串
// 子方法不会影响原有字符串
console.log(str); // abc

使用repeat传入的number有以下几种情况需要注意

1
2
3
4
5
6
7
8
9
10
11
// number 为小数,则向下取整
console.log(str.repeat(2.5)); // abcabc

// number 为负数或无穷大,则会报错
// console.log(str.repeat(-1)); // Invalid count value

// number 为NaN,则为0
console.log(str.repeat(NaN)); // ''

// number 参数为字符串,则先转换为数字值
console.log(str.repeat("2")); // abcabc

模板字符串

普通字符串使用单引号或者双引号,而模板字符串使用反引号。常用用法:

1
2
3
4
5
6
7
8
9
10
11
12
// 1. 与变量配合使用
let name = "xiaokang";
let str3 = `My name is ${name}`; // this is string this is string
console.log(str3);
// 2. 模板字符串里的字符会原样输出
let str4 = `Hello
World`;
console.log(str4);
/*
Hello
World
*/

image-20201026091739564

带标签的模板字符串

不是模板字符串的用法,而是函数调用的一种特殊形式

1
2
let str = "console";
console.log`this is ${str}`; // [ 'this is ', '' ] console

其实际上是作为函数的参数传入到函数中。

1
2
3
4
5
6
function fn(arg) {
console.log(arg);
}
fn("str"); // str
fn(`str`); // str
fn`str`; // [ 'str' ] 数组

原始字符串

1
2
3
4
5
function fn(arg) {
console.log(arg.raw);
}
fn`this is function.`; // [ 'this is function.' ]

原始字符串应用在带标签的模板字符串

函数的第一个参数中,存在着raw属性用于获取模板字符串的原始字符串

原始字符串是指:模板字符串被定义时的内容,而不是处理之后的内容