ES15:字符串相关的
一、String.prototype.isWellFormed()
isWellFormed() 让你能够测试一个字符串是否是格式正确的(即不包含单独代理项)。
“单独代理项(lone surrogate)”是指满足以下描述之一的 16 位码元:
它在范围 0xD800 到 0xDBFF 内(含)(即为前导代理),但它是字符串中的最后一个码元,或者下一个码元不是后尾代理。
它在范围 0xDC00 到 0xDFFF 内(含)(即为后尾代理),但它是字符串中的第一个码元,或者前一个码元不是前导代理。
const strings = [
// 单独的前导代理
"ab\uD800",
"ab\uD800c",
// 单独的后尾代理
"\uDFFFab",
"c\uDFFFab",
// 格式正确
"abc",
"ab\uD83D\uDE04c",
];
for (const str of strings) {
console.log(str.isWellFormed());
}
// 输出:
// false
// false
// false
// false
// true
// true
二、String.prototype.toWellFormed()
toWellFormed() 方法返回一个字符串,其中该字符串的所有单独代理项都被替换为 Unicode 替换字符 U+FFFD。
const strings = [
// 单独的前导代理
"ab\uD800",
"ab\uD800c",
// 单独的后尾代理
"\uDFFFab",
"c\uDFFFab",
// 格式正确
"abc",
"ab\uD83D\uDE04c",
];
for (const str of strings) {
console.log(str.toWellFormed());
}
// Logs:
// "ab�"
// "ab�c"
// "�ab"
// "c�ab"
// "abc"
// "ab😄c"
- isWellFormed 方法用于检测字符串是否包含无效的 Unicode 序列。
- toWellFormed 方法用于修复字符串中的无效Unicode 序列,将其替换为 Unicode 替换字符。
三、String.prototype.replaceAll()
replaceAll 方法用于替换所有匹配的子字符串,而不是仅替换第一个匹配项。
const text = 'Hello World! Hello Everyone!';
// 替换所有匹配的子字符串,所有的 Hello 都被替换为 Hi
const newText = text.replaceAll('Hello', 'Hi');
console.log(newText); // 输出: 'Hi World! Hi Everyone!'
四、String.prototype.at()
at 方法用于根据索引值获取字符串中的字符,可以使用负索引值从字符串末尾开始。
const text = 'Hello World!';
// 使用正索引值获取字符
const charAtIndex5 = text.at(5);
console.log(charAtIndex5); // 输出: ' '
// 使用负索引值获取字符
const charAtIndexMinus1 = text.value.at(-1);
console.log(charAtIndexMinus1); // 输出: '!'