欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > ES6字符串的新增方法

ES6字符串的新增方法

2025/9/19 18:55:27 来源:https://blog.csdn.net/Ght19970126/article/details/143734897  浏览:    关键词:ES6字符串的新增方法

写在前面

在ES6中,JavaScript的字符串对象得到了许多有用的新方法。这些方法使得字符串操作更加方便和强大。以下是这些新方法的详细介绍和示例。

String.fromCodePoint()

String.fromCodePoint() 方法可以将一个或多个 Unicode 码点转换为字符串。例如:

console.log(String.fromCodePoint(0x1F600)); // "😀"
console.log(String.fromCodePoint(0x1F600, 0x1F64C)); // "😀🙌"
String.raw()

String.raw() 方法可以创建一个原始字符串,忽略所有的转义字符。例如:

const template = String.raw`Hello, ${name}!`;
console.log(template); // "Hello, ${name}!"
实例方法:codePointAt()

codePointAt() 方法返回指定索引处的 Unicode 码点。例如:

const str = "Hello";
console.log(str.codePointAt(0)); // 72
console.log(str.codePointAt(1)); // 101
实例方法:normalize()

normalize() 方法可以将字符串转换为 Unicode 规范化形式。例如:

const str = "café";
console.log(str.normalize("NFC")); // "café"
console.log(str.normalize("NFD")); // "café"
实例方法:includes(), startsWith(), endsWith()

这三个方法用于检查字符串中是否包含指定的子字符串。例如:

const str = "Hello, world!";
console.log(str.includes("world")); // true
console.log(str.startsWith("Hello")); // true
console.log(str.endsWith("world!")); // true
实例方法:repeat()

repeat() 方法可以将字符串重复指定的次数。例如:

const str = "Hello";
console.log(str.repeat(3)); // "HelloHelloHello"
实例方法:padStart(),padEnd()

这两个方法可以在字符串的开头或结尾添加指定的填充字符,直到达到指定的长度。例如:

const str = "Hello";
console.log(str.padStart(10, " ")); // "     Hello"
console.log(str.padEnd(10, " ")); // "Hello     "
实例方法:trimStart(),trimEnd()

这两个方法可以从字符串的开头或结尾删除空格。例如:

const str = "   Hello, world!   ";
console.log(str.trimStart()); // "Hello, world!   "
console.log(str.trimEnd()); // "   Hello, world!"
实例方法:matchAll()

matchAll() 方法可以返回一个迭代器,用于遍历字符串中所有匹配的正则表达式。例如:

const str = "The quick brown fox jumps over the lazy dog.";
const regex = /the/gi;
const matches = str.matchAll(regex);
for (const match of matches) {console.log(match);
}
// Output: ["The", "the"]
实例方法:replaceAll()

replaceAll() 方法可以用来替换字符串中所有匹配的子字符串。例如:

const str = "The quick brown fox jumps over the lazy dog.";
console.log(str.replaceAll("the", "a")); // "a quick brown fox jumps over a lazy dog."
实例方法:at()

at() 方法可以用来获取字符串中指定索引处的字符。例如:

const str = "Hello";
console.log(str.at(0)); // "H"
console.log(str.at(1)); // "e"
实例方法:toWellFormed()

toWellFormed() 方法可以用来将一个可能包含不合法 Unicode 序列的字符串转换为一个合法的 Unicode 字符串。例如:

const str = "\u{D800}\u{DC00}"; // 不合法的 Unicode 序列
console.log(str.toWellFormed()); // "

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词