Skip to content

ES6 - 新的 String 方法

ECMAScript 2015 (ES6) 及后续版本引入了几个新的字符串方法和特性,使字符串操作更加强大和便捷。

序号方法及描述
1String.prototype.startsWith(searchString, position?)
2String.prototype.endsWith(searchString, length?)
3String.prototype.includes(searchString, position?)
4String.prototype.repeat(count)
const message = "Hello, ES6 world!";
console.log(message.startsWith("Hello")); // true
console.log(message.startsWith("ES6", 7)); // true (从索引 7 开始搜索)
console.log(message.endsWith("world!")); // true
console.log(message.endsWith("ES6", 10)); // true (考虑字符串到索引 10 为止的部分: "Hello, ES6")
console.log(message.includes("ES6")); // true
console.log(message.includes("Python")); // false
const repeatedStars = "*".repeat(5);
console.log(repeatedStars); // "*****"

模板字面量(Template literals)是字符串创建的一个强大特性,使用反引号(`)而不是单引号或双引号括起来。它们提供了几个优点:

  • 字符串插值: 使用 ${expression} 语法轻松地在字符串中嵌入表达式(变量、函数调用等)。
  • 多行字符串: 字符串可以跨越多行,无需使用 \n 等特殊字符。
const greeting = `Hello World!`;
console.log(greeting); // "Hello World!"
const name = "Brendan";
console.log(`Hello, ${name}!`); // 输出: Hello, Brendan!
const a = 10;
const b = 10;
console.log(`The sum of ${a} and ${b} is ${a + b}.`); // 输出: The sum of 10 and 10 is 20.
function getFramework() {
return "React";
}
console.log(`Current framework: ${getFramework()}!`); // 输出: Current framework: React!
const multiLineString = `This is
a string
with multiple
lines.`;
console.log(multiLineString);
// 输出:
// This is
// a string
// with multiple
// lines.

模板字面量可以带有函数名称前缀(称为“标签”)。标签函数会处理模板字面量,接收字符串部分和求值后的表达式作为参数。这允许进行高级的字符串操作和构建。

String.raw 是一个内置的标签函数,允许您获取模板字面量的原始字符串形式,这意味着反斜杠(\)没有特殊含义(例如,\n 被视为两个字符 \ 和 n,而不是换行符)。

C:\Development\profile\settings.json
const filePath = `C:\Development\profile\settings.json`;
console.log(filePath);
// 输出(转义字符被解释):
const rawFilePath = String.raw`C:\Development\profile\settings.json`;
console.log(rawFilePath);
// 输出(原始字符串):
// C:\Development\profile\settings.json

静态方法 String.fromCodePoint() 返回一个使用指定的 Unicode code points 序列创建的字符串。这对于从基本多文种平面(BMP)之外的字符创建字符串很有用,这些字符可能需要两个 UTF-16 code units(一个代理对,surrogate pair)。

console.log(String.fromCodePoint(42)); // "*"
console.log(String.fromCodePoint(65, 90)); // "AZ"
console.log(String.fromCodePoint(0x2F804)); // 一个 CJK 字符: "你" (U+2F804)
// For comparison, String.fromCharCode() would fail with values > 0xFFFF
// 对比:String.fromCharCode() 无法处理大于 0xFFFF 的值
// console.log(String.fromCharCode(0x2F804)); // 错误输出或错误

这些新特性显著增强了开发者在 JavaScript 中处理字符串的方式,使得代码更具可读性和表达力。