方法
includes()
:::info 判断字符串中是否存在某个字符,返回布尔值 :::
const str = "abcdefg";console.log(str.includes("a")); // true
startsWith() / endsWith()
:::info 判断字符串是否是以某个值开头/结尾,返回布尔值 :::
const str = "abcdefg";console.log(str.startsWith("abc")); // trueconsole.log(str.endsWith("fg")); // true
repeat()
:::info 将字符串重复多少次,返回更改后的字符串 :::
const str = "abcdefg";console.log(str.repeat(3)); // abcdefgabcdefgabcdefgconsole.log(str); // abcdefg
特殊值:
console.log("abc".repeat(2.3)); // abcabc 转换为整数2console.log("abc".repeat(NaN)); // abc 不进行操作
padStart() / padEnd()
:::info
在字符串前面/后面把某字符串填充多少次,返回新字符串
参数1:当前字符串需要填充到的目标长度。如果这个数值小于当前字符串的长度,则返回当前字符串本身
参数2:填充字符串
:::
const str = "abcdefg";console.log(str.padStart(10, "***")); // ***abcdefg 从g往前数console.log(str); // abcdefg
const str = "abcdefg";console.log(str.padEnd(10, "*")); // abcdefg*** 从a往后数console.log(str); // abcdefg
模版字符串
ES5的时候如果字符串想要拼接多个变量需要频繁的使用+
let name = "web";let info = "developer";let str = "I am a " + name + " " + info;console.log(str); // I am a web developer
这样的写法非常的不方便,ES6新增了模版字符串,用```包裹,${}`表示变量:
let name = "web";let info = "developer";let str = `I am a ${name} ${info}`;console.log(str); // I am a web developer
模版字符串内还可以是表达式:
let x = 1;let y = 2;let z = `${x} + ${y} = ${x + y}`;console.log(z); // 1 + 2 = 3
模版字符串内还可以是函数:
function fn() {return "Hello Word";}console.log(`foo ${fn()} bar`); // foo Hello Word bar
模版字符串嵌套字符串:
let msg = `Hello ${'palce'}`;console.log(msg); // Hello palce
例如我想实现一个html的数据模版:
const temp = (arr) => `<table>${arr.map((el) =>`<tr><td>${el.firstName}</td><td>${el.lastName}</td></tr>`).join("")}</table>`;const data = [{firstName: "zhang",lastName: "san",},{firstName: "li",lastName: "si",},];console.log(temp(data));
标签模版
在模版字符串的前面紧挨一个函数名表示模版字符串的标签模版,标签模版是函数调用的一种特殊形式。「标签」指的就是函数,紧跟在后面的模板字符串就是它的参数。
但是,如果模板字符里面有变量,就不是简单的调用了,而是会将模板字符串先处理成多个参数,再调用函数。
let a = 5;let b = 10;testFun`Hello ${a + b} world ${a * b}`;// 等同于 testFun(['Hello ', ' world ', ''], 15, 50);function testFun($, $1, $2) {console.log($); // ['Hello ', ' world ', '']console.log($1); // 15console.log($2); // 50}
:::info 参数1是模板字符串中那些没有变量替换的部分,也就是说,变量替换只发生在数组的第一个成员与第二个成员之间、第二个成员与第三个成员之间,以此类推。 :::
所以我们可以在标签模版函数中做一些处理后返回数据:
let a = 5;let b = 10;let str = testFun`Hello ${a + b} world ${a * b}`;function testFun($, $1, $2) {return "这是一个测试案例";}console.log(str); // "这是一个测试案例"
