🚀 26 个内置字符串方法 | JavaScript
您可以在这里观看视频版本,或者继续向下滚动查看代码片段。
⏰ 视频描述里有所有时间戳的链接,方便你跳转到感兴趣的部分。💜
🔗 所有标题均为 MDN 文档的链接。
字符
返回指定索引处的字符。
"Hello World".charAt(2); // returns "l"
// If we pass no value it defaults to an index of 0
"Hello World".charAt(); // returns "H"
// If we add an index that is undefined we get an empty string
"Hello World".charAt(20); // returns ""
charCodeAt
返回指定索引处字符的 Unicode 编码。
"Hello world".charCodeAt(2); // returns 72 for "l"
// If we pass no value it defaults to an index of 0
"Hello world".charCodeAt(); // returns 108 for "H"
连接
连接两个或多个字符串,并返回一个连接后的字符串。
它与+在字符串上使用运算符非常相似。
"Hello".concat(" world"); // returns "Hello world"
// With multiple strings
"Hello".concat(" world", " and", " other", " planets"); // returns "Hello world and other planets"
以……结尾
检查字符串是否以指定的字符串结尾。我们可以添加一个可选的第二个参数,用于设置字符串的长度限制。
"Dogs are the best!".endsWith('best'); // returns false
"Dogs are the best!".endsWith('best!'); // returns true
// With second parameter for ending index
"Dogs are the best!".endsWith('best', 17); // returns true (because we picked the end of the string is at index 17)
来自字符代码
将 Unicode 值转换为可读字符。fromCharCode这是字符串对象上为数不多的静态方法之一。我们之前使用的其他方法都是所谓的实例属性。我们可以使用String关键字来访问它。
String.fromCharCode(67); // returns "C"
// Using multiple characters
String.fromCharCode(67, 111, 100, 250); // returns "Codú"
包括
检查字符串是否包含特定字符串。
"Dogs are the best!".includes("Dogs") // returns true
// With optional starting index
"Dogs are the best!".includes("Dogs", 1) // returns false
"Dogs are the best!".includes("ogs", 1) // returns true
索引
返回指定值在字符串中首次出现的位置。
"test one two test".indexOf("test") // returns 0
"test one two test".indexOf("x") // returns -1
// With optional starting index
"test one two test".indexOf("test", 1) // returns 13
lastIndexOf
返回指定值最后一次出现在字符串中的位置。
"test one two test".lastIndexOf("test") // returns 13
// With optional limit because search starts from index 12.
"test one two test".lastIndexOf("test", 12) // returns 0
匹配
match() 方法检索字符串与正则表达式或字符串匹配的结果。
// returns the first match
"This is the BEST".match("i"); // returns a regex iterator like this ["i", index: 2, input: "This is the BEST", groups: undefined]
// With a regex looking for uppercase characters
"This is the BEST".match(/[A-Z]/); // returns a regex iterator like this ["T", index: 0, input: "This is the BEST", groups: undefined]
// you can get all the matches without the details if you use a global regular expression
"This is the BEST".match(/[A-Z]/g); // returns [ 'T', 'B', 'E', 'S', 'T' ]
匹配所有
这是 ES2020 的一个新特性,请检查您的浏览器兼容性。matchAll方法类似于功能更强大的 match 方法,它会返回RegExpStringIterator匹配项。
// Working with with the RegExpStringIterator can become easy to work with if we spread it into an array.
const matches = [..."This is the BEST".matchAll(/[A-Z]/g)];
matches.forEach(element => console.log(element));
/*
console.logs
[ 'T', index: 0, input: 'This is the BEST', groups: undefined ]
[ 'B', index: 12, input: 'This is the BEST', groups: undefined ]
[ 'E', index: 13, input: 'This is the BEST', groups: undefined ]
[ 'S', index: 14, input: 'This is the BEST', groups: undefined ]
[ 'T', index: 15, input: 'This is the BEST', groups: undefined ] */
有关使用迭代器的更多信息,请查看文档。
规范化
我们可以使用 normalize 函数对 Unicode 字符串进行规范化,这是什么意思呢?基本上就是让我们能够以人类可读的形式查看它。
"\u0043\u006f\u0064\u00fa".normalize(); // returns "Codú"
padEnd
我们可以给字符串末尾添加“填充”,使其达到指定长度。默认情况下使用空格填充,但也可以选择替换字符。
// Entire length is 10 after padding
"Hello".padEnd(10); // returns "Hello "
// Entire length is 10 after padding with characters too
"Hello".padEnd(10, "*"); // returns "Hello*****"
padStart
我们可以给字符串开头添加“填充”,使其达到指定长度。默认情况下使用空格填充,但也可以选择替换字符。
// Entire length is 10 after padding
"Hello".padStart(10); // returns " Hello"
// Entire length is 10 after padding with characters too
"Hello".padStart(10, "*"); // returns "*****Hello"
这些填充看起来可能无关紧要,但之前有个很火的库因为使用了这种填充方式而被 npm 下架,结果几乎让整个网络瘫痪。你可以搜索“left-pad incident”了解详情。
重复
接受一个数字作为参数,并将字符串重复指定的次数,然后作为单个字符串返回。
"Hello".repeat(3); // returns "HelloHelloHello".
代替
此函数会在字符串中搜索指定值或正则表达式,并返回一个新字符串,其中指定的值已被替换。我们可以用一个字符串替换这些值,也可以传递一个函数来处理匹配项。除非我们传递一个全局正则表达式,否则它只会替换找到的第一个匹配项。
"cat, cat, cat".replace(/cat/, 'dog'); // returns "dog, cat, cat"
"cat, cat, cat".replace(/cat/g, 'dog'); // returns "dog, dog, dog"
"cat, cat, cat".replace("cat", 'dog'); // returns "dog, cat, cat"
"cat, cat, cat, bird".replace("cat", (i) => i + "dog"); // returns "catdog, cat, cat, bird"
全部替换
我们可以使用正则表达式或字符串来替换字符串的所有实例。我们可以用字符串替换这些值,也可以传递一个函数来处理匹配项。使用全局正则表达式时,`replace all`replace和 ` replace all` 的区别不大replaceAll。`replace all` 只接受全局正则表达式,但如果您传递一个字符串,它会自动替换该字符串的所有实例。第二个参数可以是要替换每个实例的字符串,也可以是要对每个实例进行操作的函数。
"cat, cat, cat, bird".replaceAll(/cat/g, 'dog'); // returns "dog, dog, dog, bird"
"cat, cat, cat, bird".replaceAll("cat", 'dog'); // returns "dog, dog, dog, bird"
// With a function
"cat, cat, cat, bird".replaceAll("cat", (i) => i + "dog"); // returns "catdog, catdog, catdog, bird"
搜索
在字符串中搜索指定的值或正则表达式,并返回匹配的起始位置。
"cat, dog, cat".search("dog"); // returns 5
// With a regex
"cat, dog, cat".search(/dog/g); // returns 5
片
提取字符串的一部分并返回一个新字符串。
"This is a string I want to slice".slice(27); // returns 'slice'
"This is a string I want to slice".slice(27, 28); // returns 's'
// And we can work backwards with negative values such as
"This is a string I want to slice".slice(-5); // returns "slice"
"This is a string I want to slice".slice(-5, -1); // returns "slic"
分裂
将字符串分割成子字符串数组。我们可以将可选的分割限制作为第二个参数。
// For all characters to be split give an empty string
"Hello darkness".split(""); // returns ["H", "e", "l", "l", "o", " ", "d", "a", "r", "k", "n", "e", "s", "s"]
// To split at spaces
"Hello darkness my old friend".split(" "); // returns ["Hello", "darkness", "my", "old", "friend"]
To limit the return length we can use an optional second parameter
"Hello darkness my old friend".split(" ", 2); // returns ["Hello", "darkness"]
以
检查字符串是否以指定的字符开头,并返回布尔值。我们可以将起始索引作为第二个参数(可选)。
"Hello".startsWith("h"); // true
"Hello".startsWith("e"); // false
// With optional starting index
"Hello".startsWith("e", 1); // true
子字符串
从字符串中提取指定索引之间的字符。第二个参数是可选的。
"Hello".substring(1, 4); // "ell"
// If we give no second parameter it will pick assume you have no end index.
"Hello".substring(1); // returns "ello"
转换为小写
将字符串转换为小写字母
"HeLlO wOrLd".toLowerCase(); // returns "hello world"
转换为大写
将字符串转换为大写字母。
"Hello world".toUpperCase(); // returns "HELLO WORLD"
修剪
删除字符串两端的空格。
" Hello world ".trim(); // returns "Hello world"
修剪结束
去掉末尾的空白。
" Hello world ".trim(); // returns " Hello world"
trimStart
删除字符串开头的空白字符。
" Hello world ".trim(); // returns "Hello world "
订阅Codú 社区
文章来源:https://dev.to/nialljoemaher/26-built-in-string-methods-javascript-56p