# 1. 字符串插值

最后尤为重要的是拼接字符串的新方法。如果你想在一个辅助程序中构建模版字符串,这会非常有用。它使动态连接字符串模版变得更简单了。

const user = {
  name: "John",
  surname: "Doe",
  details: {
    email: "john@doe.com",
    displayName: "SuperCoolJohn",
    joined: "2016-05-05",
    image: "path-to-the-image",
    followers: 45,
  },
};
const printUserInfo = (user) => {
  const text = `The user is ${user.name} ${user.surname}. Email: ${user.details.email}. Display Name: ${user.details.displayName}. ${user.name} has ${user.details.followers} followers.`;
  console.log(text);
};
printUserInfo(user);
// 输出 'The user is John Doe. Email: john@doe.com. Display Name: SuperCoolJohn. John has 45 followers.'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 2.字符串替换

String.replace()函数允许你使用字符串或正则表达式来替换字符串,本身这个函数只替换第一次出现的字符串,不过你可以使用正则表达多中的/g 来模拟 replaceAll()函数功能:

var string = "john john";
console.log(string.replace(/hn/, "ana")); // "joana john"
console.log(string.replace(/hn/g, "ana")); // "joana joana"
1
2
3

# 3.一句代码求字符串反转

let str = "hello 秦爱德";
console.log([...str].reverse().join("")); //德爱秦 olleh
1
2

# 4.一句代码统计字符串中相同字符出现的次数

let str = "aaabbbccddeegggggggllllssgjwd";
let strInfo = str.split("").reduce((p, c) => (p[c]++ || (p[c] = 1), p), {});
console.log(strInfo);
/*
a: 3
b: 3
c: 2
d: 3
e: 2
g: 8
j: 1
l: 4
s: 2
w: 1
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 5.隐式转义(字符串转数字)

let a = "1";
console.log(Number(a));
console.log(+a);
// 使用隐式转义可更简单快速
1
2
3
4

# 6.用字符串返回一个键盘图形 惊 😮!!!

console.log(
  ((_) =>
    [..."`1234567890-=~~QWERTYUIOP[]\\~ASDFGHJKL;'~~ZXCVBNM,./~"].map(
      (x) =>
        ((o += `/${(b = "_".repeat(
          (w =
            x < y
              ? 2
              : " 667699"[
                  ((x = ["BS", "TAB", "CAPS", "ENTER"][p++] || "SHIFT"), p)
                ])
        ))}\\|`),
        (m += y + (x + "    ").slice(0, w) + y + y),
        (n += y + b + y + y),
        (l += " __" + b))[73] &&
        (k.push(l, m, n, o), (l = ""), (m = n = o = y)),
      (m = n = o = y = "|"),
      (p = l = k = [])
    ) &&
    k.join`
`)()
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# 7.通过模板字面量(template literals)进行简单的模板解析

ES6 的模板字面量与文字模板相比,更接近于字符串字面量。但是,如果你将它们通过函数返回,你可以使用他们来做简单的模板渲染:

const tmpl = (addrs) => ` 
    ${addrs
      .map(
        (addr) => `
        ${addr.first}${addr.last}
    `
      )
      .join("")} 
`;
const data = [
  { first: "", last: "Bond" },
  { first: "Lars", last: "" },
];
console.log(tmpl(data));
// Output:
// //
//
//     Bond
//
//     Lars
//
//
//
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

tmpl 函数将数组 addrs 用 map(通过箭头函数) join 拼成字符串。tmpl() 可以批量插入数据到表格中: