Appearance
JS String
1. 静态方法
1.1. fromCharCode(1*num)
String.fromCharCode() 静态方法返回由指定的 UTF-16 码元序列创建的字符串。
参数
num:一个介于 0 和 65535(0xFFFF)之间的数字,表示一个 UTF-16 码元。大于 0xFFFF 的数字会被截断为最后的 16 位。不进行有效性检查。
返回值
一个长度为 N 的字符串,由 N 个指定的 UTF-16 码元组成。
示例
JavaScript
console.log(String.fromCharCode(189, 43, 190, 61));
// Expected output: "½+¾="1.2. fromCodePoint(1*num)
String.fromCodePoint() 静态方法将根据指定的码位序列返回一个字符串。
参数
num:一个介于 0 和 0x10FFFF(包括两者)之间的整数,表示一个 Unicode 码位。
返回值
通过使用指定的码位序列创建的字符串。
示例
JavaScript
console.log(String.fromCodePoint(9731, 9733, 9842, 0x2f804));
// Expected output: "☃★♲你"2. 实例方法
2.1. at(index)
at() 方法接受一个整数值,并返回一个新的 String,该字符串由位于指定偏移量处的单个 UTF-16 码元组成。该方法允许正整数和负整数。负整数从字符串中的最后一个字符开始倒数。
参数
index:要返回的字符串字符的索引(位置)。当传递负数时,支持从字符串末端开始的相对索引;也就是说,如果使用负数,返回的字符将从字符串的末端开始倒数。
返回值
由位于指定位置的单个 UTF-16 码元组成的 String。如果找不到指定的索引,则返回 undefined。
示例
JavaScript
// 返回给定字符串的最后一个字符的函数
function returnLast(arr) {
return arr.at(-1);
}
let invoiceRef = "myinvoice01";
console.log(returnLast(invoiceRef));
// Logs: '1'
invoiceRef = "myinvoice02";
console.log(returnLast(invoiceRef));
// Logs: '2'1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
2.2. charAt(index)
String 的 charAt() 方法返回一个由给定索引处的单个 UTF-16 码元构成的新字符串。
charAt() 方法总是将字符串作为 UTF-16 码元序列进行索引,因此它可能会返回孤项代理。要获取给定索引处的完整 Unicode 码位,请使用 String.prototype.codePointAt() 和 String.fromCodePoint()。
Note
at与charAt方法的区别
at方法更加灵活,支持负索引,并且在索引超出范围时返回undefined;charAt方法是传统方法,只支持正索引,并且在索引超出范围时返回空字符串;
参数
index:要返回的字符的索引,从零开始。会被转换为整数 —— undefined 会被转换为 0。
返回值
返回一个字符串,该字符串表示指定 index 处的字符(恰好是一个 UTF-16 码元)。如果 index 超出了 0 – str.length - 1 的范围,charAt() 将返回一个空字符串。
示例
JavaScript
const sentence = 'The quick brown fox jumps over the lazy dog.';
const index = 4;
console.log(`The character at index ${index} is ${sentence.charAt(index)}`);
// Expected output: "The character at index 4 is q"1
2
3
4
5
6
2
3
4
5
6
2.3. charCodeAt(index)
String 的 charCodeAt() 方法返回一个整数,表示给定索引处的 UTF-16 码元,其值介于 0 和 65535 之间。
charCodeAt() 方法总是将字符串当作 UTF-16 码元序列进行索引,因此它可能返回单独代理项(Lone Surrogate)。如果要获取给定索引处的完整 Unicode 码位,请使用 String.prototype.codePointAt() 方法。
参数
index:要返回的字符的索引,从零开始。将被转换为整数 —— undefined 被转换为 0。
返回值
一个整数,介于 0 和 65535 之间,表示指定 index 处字符的 UTF-16 码元值。如果 index 超出了 0 到 str.length - 1 的范围,则 charCodeAt() 返回 NaN。
示例
JavaScript
const sentence = 'The quick brown fox jumps over the lazy dog.';
const index = 4;
console.log(
`Character code ${sentence.charCodeAt(index)} is equal to ${sentence.charAt(
index,
)}`,
);
// Expected output: "Character code 113 is equal to q"1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
2.4. codePointAt(index)
String 的 codePointAt() 方法返回一个非负整数,该整数是从给定索引开始的字符的 Unicode 码位值。请注意,索引仍然基于 UTF-16 码元,而不是 Unicode 码位。
参数
index:需要返回的字符的(从零开始的)索引。会被转换为整数 —— undefined 会转换为 0。
返回值
一个非负整数,表示给定 index 处字符的码位值。
- 如果
index超出了0–str.length - 1的范围,codePointAt()返回undefined; - 如果
index处的元素是一个 UTF-16 前导代理(Leading Surrogate),则返回代理对的码位; - 如果
index处的元素是一个 UTF-16 后尾代理(Trailing Surrogate),则只返回后尾代理的码元;
示例
JavaScript
const icons = '☃★♲';
console.log(icons.codePointAt(1));
// Expected output: "9733"1
2
3
4
2
3
4
2.5. includes(searchString[, position])
String 值的 includes() 方法执行区分大小写的搜索,以确定是否可以在一个字符串中找到另一个字符串,并根据情况返回 true 或 false。
参数
searchString:一个要在str中查找的字符串。不能是正则表达式。所有非正则表达式的值都会被强制转换为字符串,因此如果该参数被省略或传入undefined,includes()方法会在字符串中搜索"undefined",这通常不是你想要的;position:在字符串中开始搜索searchString的位置。默认值为0;
返回值
如果在给定的字符串中找到了要搜索的字符串(包括 searchString 为空字符串的情况),则返回 true,否则返回 false。
示例
JavaScript
const sentence = 'The quick brown fox jumps over the lazy dog.';
const word = 'fox';
console.log(
`The word "${word}" ${
sentence.includes(word) ? 'is' : 'is not'
} in the sentence`,
);
// Expected output: "The word "fox" is in the sentence"1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
2.6. startsWith(searchString[, position])
String 的 startsWith() 方法用来判断当前字符串是否以另外一个给定的子字符串开头,并根据判断结果返回 true 或 false。
参数
searchString:要在该字符串开头搜索的子串。不能是正则表达式。所有不是正则表达式的值都会被强制转换为字符串,因此省略它或传递undefined将导致startsWith()搜索字符串"undefined",这应该不是你想要的结果。position:searchString期望被找到的起始位置(即searchString的第一个字符的索引)。默认为0。
返回值
如果给定的字符在字符串的开头被找到(包括当 searchString 是空字符串时),则返回 true;否则返回 false。
示例
JavaScript
const str1 = 'Saturday night plans';
console.log(str1.startsWith('Sat'));
// Expected output: true
console.log(str1.startsWith('Sat', 3));
// Expected output: false1
2
3
4
5
6
7
2
3
4
5
6
7
2.7. endsWith(searchString[, endPosition])
endsWith() 方法用于判断一个字符串是否以指定字符串结尾,如果是则返回 true,否则返回 false。
参数
searchString:要搜索的作为结尾的字符串,不能是正则表达式。所有非正则表达式的值都会被强制转换为字符串,因此如果该参数被省略或传入undefined,endsWith()方法会在字符串中搜索"undefined",这通常不是你想要的;endPosition:预期找到searchString的末尾位置(即searchString最后一个字符的索引加1)。默认为str.length;
返回值
如果被检索字符串的末尾出现了指定的字符串(包括 searchString 为空字符串的情况),则返回 true;否则返回 false。
示例
JavaScript
const str1 = 'Cats are the best!';
console.log(str1.endsWith('best!'));
// Expected output: true
console.log(str1.endsWith('best', 17));
// Expected output: true
const str2 = 'Is this a question?';
console.log(str2.endsWith('question'));
// Expected output: false1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
2.8. indexOf(searchString[, position])
String 的 indexOf() 方法在字符串中搜索指定子字符串,并返回其第一次出现的位置索引。它可以接受一个可选的参数指定搜索的起始位置,如果找到了指定的子字符串,则返回的位置索引大于或等于指定的数字。
参数
searchValue:要搜索的子字符串。所有传入值都会被强制转换为字符串,因此如果该参数被省略或传入undefined,indexOf()方法会在字符串中搜索"undefined",这通常不是你想要的;position:该方法返回指定子字符串在大于或等于position位置的第一次出现的索引,默认为0。如果position大于调用字符串的长度,则该方法根本不搜索调用字符串。如果position小于零,该方法的行为就像position为0时一样;
返回值
查找的字符串 searchValue 的第一次出现的索引,如果没有找到,则返回 -1。
Note 搜索空字符串时的返回值
搜索空字符串会产生奇怪的结果。如果没有第二个参数,或者第二个参数的值小于调用字符串的长度,则返回值与第二个参数的值相同:
JavaScript"hello world".indexOf(""); // 返回 0 "hello world".indexOf("", 0); // 返回 0 "hello world".indexOf("", 3); // 返回 3 "hello world".indexOf("", 8); // 返回 81
2
3
4但是,如果第二个参数的值大于或等于字符串的长度,则返回值是字符串的长度:
JavaScript"hello world".indexOf("", 11); // 返回 11 "hello world".indexOf("", 13); // 返回 11 "hello world".indexOf("", 22); // 返回 111
2
3在前一个实例中,该方法的行为就像在第二个参数指定的位置之后发现了一个空字符串。在后一个实例中,该方法的行为就好像在调用字符串的末尾找到了一个空字符串。
示例
JavaScript
const paragraph = "I think Ruth's dog is cuter than your dog!";
const searchTerm = 'dog';
const indexOfFirst = paragraph.indexOf(searchTerm);
console.log(`The index of the first "${searchTerm}" is ${indexOfFirst}`);
// Expected output: "The index of the first "dog" is 15"
console.log(
`The index of the second "${searchTerm}" is ${paragraph.indexOf(
searchTerm,
indexOfFirst + 1,
)}`,
);
// Expected output: "The index of the second "dog" is 38"1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2.9. lastIndexOf(searchString[, position])
String 的 lastIndexOf() 方法搜索该字符串并返回指定子字符串最后一次出现的索引。它可以接受一个可选的起始位置参数,并返回指定子字符串在小于或等于指定数字的索引中的最后一次出现的位置。
参数
searchString:要搜索的子字符串。所有值都会强制转换为字符串,因此如果该参数被省略或传入undefined,lastIndexOf()方法会在字符串中搜索"undefined",这通常不是你想要的。position:该方法返回指定子字符串在小于或等于position的位置中的最后一次出现的索引,默认为+Infinity。如果position大于调用字符串的长度,则该方法将搜索整个字符串。如果position小于0,则行为与0相同,即该方法只在索引0处查找指定的子字符串。
返回值
如果找到了 searchString,则返回最后一次出现的索引,否则返回 -1。
示例
JavaScript
const paragraph = "I think Ruth's dog is cuter than your dog!";
const searchTerm = 'dog';
console.log(
`Index of the last ${searchTerm} is ${paragraph.lastIndexOf(searchTerm)}`,
);
// Expected output: "Index of the last "dog" is 38"1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
2.10. localeCompare(compareString[, locales[, options]])
localeCompare() 方法返回一个数字,表示参考字符串在排序顺序中是在给定字符串之前、之后还是与之相同。在支持 Intl.Collator API 的实现中,该方法仅是调用了 Intl.Collator 方法。
当比较大量字符串时,例如对大型数组进行排序,最好创建一个 Intl.Collator 对象,并使用其 compare() 方法提供的函数。
参数
locales 和 options 参数可以自定义函数的行为,并让应用程序指定应使用哪种语言的格式约定。
在支持 Intl.Collator API 的实现中,这些参数与 Intl.Collator() 构造函数的参数完全对应。而对于不支持 Intl.Collator 的实现,应忽略这两个参数,使得返回的比较结果完全依赖于实现 —— 只要求其保持一致。
compareString:与referenceStr进行比较的字符串。所有值都会被强制转换为字符串,因此省略该参数或传入undefined会导致localeCompare()与字符串"undefined"进行比较,这通常不是你想要的;locales:表示缩写语言代码(BCP 47 language tag)的字符串,或由此类字符串组成的数组。对应于Intl.Collator()构造函数的locales参数。在不支持Intl.Collator的实现中,该参数会被忽略,并且通常会使用主机的区域设置;options:一个调整输出格式的对象。对应于Intl.Collator()构造函数的options参数。在不支持Intl.Collator的实现中,该参数会被忽略;
参见 Intl.Collator() 构造函数以详细了解 locales 和 options 参数以及如何使用它们。
返回值
如果引用字符串(referenceStr)存在于比较字符串(compareString)之前则为负数;如果引用字符串存在于比较字符串之后则为正数;相等的时候返回 0。
在支持 Intl.Collator 的实现中,此方法等价于 new Intl.Collator(locales, options).compare(referenceStr, compareString)。
示例
JavaScript
const a = 'réservé'; // With accents, lowercase
const b = 'RESERVE'; // No accents, uppercase
console.log(a.localeCompare(b));
// Expected output: 1
console.log(a.localeCompare(b, 'en', { sensitivity: 'base' }));
// Expected output: 01
2
3
4
5
6
7
2
3
4
5
6
7
2.11. match(regexp)
match() 方法检索字符串与正则表达式进行匹配的结果。
参数
regexp一个正则表达式对象或者任何具有
Symbol.match方法的对象。如果
regexp不是RegExp对象并且对象上无Symbol.match方法,则会使用new RegExp(regexp)将其隐式地转换为RegExp。如果你没有给出任何参数并直接使用
match()方法,你将会得到一个包含空字符串的数组:[""],因为这等价于match(/(?:)/)。
返回值
一个 Array,其内容取决于是否存在全局(g)标志,如果没有匹配,则返回 null。
如果使用
g标志,则将返回与完整正则表达式匹配的所有结果,但不会返回捕获组;如果没有使用
g标志,则只返回第一个完整匹配及其相关捕获组。在这种情况下,match()方法将返回与RegExp.prototype.exec()相同的结果(一个带有一些额外属性的数组);
示例
JavaScript
const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g;
const found = paragraph.match(regex);
console.log(found);
// Expected output: Array ["T", "I"]1
2
3
4
5
6
2
3
4
5
6
2.12. matchAll(regexp)
matchAll() 方法返回一个迭代器,该迭代器包含了检索字符串与正则表达式进行匹配的所有结果(包括捕获组)。
参数
regexp一个正则表达式对象,或者是任何具有
Symbol.matchAll方法的对象。如果
regexp不是一个RegExp对象,并且没有Symbol.matchAll方法,它将通过new RegExp(regexp, 'g')被隐式转换为一个RegExp对象。如果
regexp是一个正则表达式,那么它必须设置了全局(g)标志,否则会抛出TypeError异常。
返回值
一个匹配结果的可迭代迭代器对象(它不可重新开始)。每个匹配结果都是一个数组,其形状与 RegExp.prototype.exec() 的返回值相同。
示例
JavaScript
const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';
const array = [...str.matchAll(regexp)];
console.log(array[0]);
// Expected output: Array ["test1", "e", "st1", "1"]
console.log(array[1]);
// Expected output: Array ["test2", "e", "st2", "2"]1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
2.13. search(regexp)
search() 方法用于在 String 对象中执行正则表达式的搜索,寻找匹配项。
参数
regexp一个正则表达式对象,或者具有
Symbol.search方法的任意对象。如果
regexp不是RegExp对象,并且不具有Symbol.search方法,则会使用new RegExp(regexp)将其隐式转换为RegExp。
返回值
如果匹配成功,则返回正则表达式在字符串中首次匹配的索引;否则,返回 -1。
示例
JavaScript
const paragraph = "I think Ruth's dog is cuter than your dog!";
// Anything not a word character, whitespace or apostrophe
const regex = /[^\w\s']/g;
console.log(paragraph.search(regex));
// Expected output: 41
console.log(paragraph[paragraph.search(regex)]);
// Expected output: "!"1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
2.14. concat(1*str)
concat() 方法将字符串参数连接到调用的字符串,并返回一个新的字符串。
参数
str:要连接到 str 的一个或多个字符串。
返回值
一个包含所提供的多个字符串文本组合的新字符串。
示例
JavaScript
const str1 = 'Hello';
const str2 = 'World';
console.log(str1.concat(' ', str2));
// Expected output: "Hello World"
console.log(str2.concat(', ', str1));
// Expected output: "World, Hello"1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
2.15. repeat(count)
repeat() 方法构造并返回一个新字符串,其中包含指定数量的所调用的字符串副本,这些副本连接在一起。
参数
count:介于 0 和 +Infinity 之间的整数。表示在新构造的字符串中重复了多少遍原字符串。
返回值
包含指定字符串的指定数量副本的新字符串。
示例
JavaScript
const mood = 'Happy! ';
console.log(`I feel ${mood.repeat(3)}`);
// Expected output: "I feel Happy! Happy! Happy! "1
2
3
4
2
3
4
2.16. replace(pattern, replacement)
replace() 方法返回一个新字符串,其中一个、多个或所有匹配的 pattern 被替换为 replacement。pattern 可以是字符串或 RegExp,replacement 可以是字符串或一个在每次匹配时调用的函数。如果 pattern 是字符串,则只会替换第一个匹配项。原始的字符串不会改变。
参数
pattern可以是字符串或者一个带有
Symbol.replace方法的对象,典型的例子就是正则表达式。任何没有Symbol.replace方法的值都会被强制转换为字符串。replacement可以是字符串或函数。
如果是字符串,它将替换由
pattern匹配的子字符串。支持一些特殊的替换模式,请参阅下面的指定字符串作为替换项部分;如果是函数,将为每个匹配调用该函数,并将其返回值用作替换文本。下面的指定函数作为替换项部分描述了提供给此函数的参数;
返回值
一个新的字符串,其中一个、多个或所有的匹配项都被指定的替换项替换。
示例
JavaScript
const paragraph = "I think Ruth's dog is cuter than your dog!";
console.log(paragraph.replace("Ruth's", 'my'));
// Expected output: "I think my dog is cuter than your dog!"
const regex = /Dog/i;
console.log(paragraph.replace(regex, 'ferret'));
// Expected output: "I think Ruth's ferret is cuter than your dog!"1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
2.17. replaceAll(pattern, replacement)
replaceAll() 方法返回一个新字符串,其中所有匹配 pattern 的部分都被替换为 replacement。pattern 可以是一个字符串或一个 RegExp,replacement 可以是一个字符串或一个在每次匹配时调用的函数。原始字符串保持不变。
参数
pattern可以是一个字符串或一个具有
Symbol.replace方法的对象,典型的例子是正则表达式。任何没有Symbol.replace方法的值都将被强制转换为字符串。如果
pattern是一个正则表达式,则必须设置全局(g)标志,否则会抛出TypeError。replacement可以是一个字符串或一个函数。替换字符串的语义与
String.prototype.replace()相同。
返回值
返回一个新字符串,其中所有匹配 pattern 的部分都被替换为 replacement。
示例
JavaScript
const paragraph = "I think Ruth's dog is cuter than your dog!";
console.log(paragraph.replaceAll('dog', 'monkey'));
// Expected output: "I think Ruth's monkey is cuter than your monkey!"
// Global flag required when calling replaceAll with regex
const regex = /Dog/gi;
console.log(paragraph.replaceAll(regex, 'ferret'));
// Expected output: "I think Ruth's ferret is cuter than your ferret!"1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
2.18. slice(indexStart[, indexEnd])
slice() 方法提取字符串的一部分,并将其作为新字符串返回,而不修改原始字符串。
参数
indexStart:要返回的子字符串中包含的第一个字符的索引;indexEnd:要返回的子字符串中排除的第一个字符的索引;
返回值
一个包含提取的字符串片段的新字符串。
示例
JavaScript
const str = 'The quick brown fox jumps over the lazy dog.';
console.log(str.slice(31));
// Expected output: "the lazy dog."
console.log(str.slice(4, 19));
// Expected output: "quick brown fox"
console.log(str.slice(-4));
// Expected output: "dog."
console.log(str.slice(-9, -5));
// Expected output: "lazy"1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
2.19. split(separator[, limit])
split() 方法接受一个模式,通过搜索模式将字符串分割成一个有序的子串列表,将这些子串放入一个数组,并返回该数组。
参数
separator描述每个分割应该发生在哪里的模式。可以是
undefined,一个字符串,或者一个具有Symbol.split方法的对象 —— 典型的例子是正则表达式。省略separator或传递undefined会导致split()返回一个只包含所调用字符串数组。所有不是undefined的值或不具有[Symbol.split]()方法的对象都被强制转换为字符串。limit一个非负整数,指定数组中包含的子字符串的数量限制。当提供此参数时,
split方法会在指定separator每次出现时分割该字符串,但在已经有limit个元素时停止分割。任何剩余的文本都不会包含在数组中。- 如果在达到极限之前就达到了字符串的末端,那么数组包含的条目可能少于
limit; - 如果
limit为0,则返回[];
- 如果在达到极限之前就达到了字符串的末端,那么数组包含的条目可能少于
返回值
在给定字符串中出现 separator 的每一个点上进行分割而成的字符串数组。
示例
JavaScript
const str = 'The quick brown fox jumps over the lazy dog.';
const words = str.split(' ');
console.log(words[3]);
// Expected output: "fox"
const chars = str.split('');
console.log(chars[8]);
// Expected output: "k"
const strCopy = str.split();
console.log(strCopy);
// Expected output: Array ["The quick brown fox jumps over the lazy dog."]1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
2.20. substring(indexStart[, indexEnd])
String 的 substring() 方法返回该字符串从起始索引到结束索引(不包括)的部分,如果未提供结束索引,则返回到字符串末尾的部分。
参数
indexStart:返回子字符串中第一个要包含的字符的索引;indexEnd:返回子字符串中第一个要排除的字符的索引;
返回值
包含给定字符串的指定部分的新字符串。
示例
JavaScript
const str = 'Mozilla';
console.log(str.substring(1, 3));
// Expected output: "oz"
console.log(str.substring(2));
// Expected output: "zilla"1
2
3
4
5
6
7
2
3
4
5
6
7
2.21. padEnd(targetLength[, padString])
padEnd() 方法会将当前字符串从末尾开始填充给定的字符串(如果需要会重复填充),直到达到给定的长度。填充是从当前字符串的末尾开始的。
参数
targetLength:当前str填充后的长度。如果该值小于或等于str.length,则会直接返回当前str;padString:用于填充当前str的字符串。如果padString太长,无法适应targetLength,则会被截断:对于从左到右的语言,左侧的部分将会被保留;对于从右到左的语言,右侧的部分将会被保留。默认值为 “ ” (U+0020);
返回值
在当前 str 末尾填充 padString 直到达到给定的 targetLength 所形成的 String。
示例
JavaScript
const str1 = 'Breaded Mushrooms';
console.log(str1.padEnd(25, '.'));
// Expected output: "Breaded Mushrooms........"
const str2 = '200';
console.log(str2.padEnd(5));
// Expected output: "200 "1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
2.22. padStart(targetLength[, padString])
padStart() 方法用另一个字符串填充当前字符串(如果需要会重复填充),直到达到给定的长度。填充是从当前字符串的开头开始的。
参数
targetLength;当前str填充后的长度。如果该值小于或等于str.length,则会直接返回当前str;padString;用于填充当前str的字符串。如果padString太长,无法适应targetLength,则会从末尾被截断。默认值为 Unicode “空格” 字符(U+0020);
返回值
在开头填充 padString 直到达到给定的 targetLength 所形成的 String。
示例
JavaScript
const str1 = '5';
console.log(str1.padStart(2, '0'));
// Expected output: "05"
const fullNumber = '2034399002125581';
const last4Digits = fullNumber.slice(-4);
const maskedNumber = last4Digits.padStart(fullNumber.length, '*');
console.log(maskedNumber);
// Expected output: "************5581"1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
2.23. trim()
String 的 trim() 方法会从字符串的两端移除空白字符,并返回一个新的字符串,而不会修改原始字符串。
要返回一个仅从一端修剪空白字符的新字符串,请使用 trimStart() 或 trimEnd()。
返回值
一个新的字符串,表示从 str 的开头和结尾去除空白字符后的结果。空白字符定义为空白符加上行终止符。
如果 str 的开头和结尾都没有空白字符,仍然会返回一个新的字符串(实际上是 str 的副本)。
示例
JavaScript
const greeting = ' Hello world! ';
console.log(greeting);
// Expected output: " Hello world! ";
console.log(greeting.trim());
// Expected output: "Hello world!";1
2
3
4
5
6
7
2
3
4
5
6
7
2.24. trimEnd()
String 的 trimEnd() 方法会从字符串的结尾移除空白字符,并返回一个新的字符串,而不会修改原始字符串。trimRight() 是该方法的别名。
返回值
一个新的字符串,表示从 str 的末尾(右侧)去除空白字符后的结果。空白字符定义为空白符加上行终止符。
如果 str 的末尾没有空白字符,仍然会返回一个新的字符串(实际上是 str 的副本)。
示例
JavaScript
const greeting = ' Hello world! ';
console.log(greeting);
// Expected output: " Hello world! ";
console.log(greeting.trimEnd());
// Expected output: " Hello world!";1
2
3
4
5
6
7
2
3
4
5
6
7
2.25. trimStart()
String 的 trimStart() 方法会从字符串的开头移除空白字符,并返回一个新的字符串,而不会修改原始字符串。trimLeft() 是该方法的别名。
返回值
一个新的字符串,表示从 str 的开头(左侧)去除空白字符后的结果。空白字符定义为空白符加上行终止符。
如果 str 的开头没有空白字符,仍然会返回一个新的字符串(实际上是 str 的副本)。
示例
JavaScript
const greeting = ' Hello world! ';
console.log(greeting);
// Expected output: " Hello world! ";
console.log(greeting.trimStart());
// Expected output: "Hello world! ";1
2
3
4
5
6
7
2
3
4
5
6
7
2.26. isWellFormed()
String 值的 isWellFormed() 方法返回一个表示该字符串是否包含单独代理项的布尔值。
返回值
如果字符串不包含单独代理项,返回 true,否则返回 false。
示例
JavaScript
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
// true1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2.27. toWellFormed()
String 的 toWellFormed() 方法返回一个字符串,其中该字符串的所有单独代理项都被替换为 Unicode 替换字符 U+FFFD。
返回值
新的字符串是原字符串的一个拷贝,其中所有的单独代理项被替换为 Unicode 替换字符 U+FFFD。如果 str 是格式正确的,仍然会返回一个新字符串(本质上是 str 的一个拷贝)。
示例
JavaScript
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"1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2.28. normalize([form])
String 的 normalize() 方法返回该字符串的 Unicode 标准化形式。
参数
form:是 "NFC"、"NFD"、"NFKC" 或 "NFKD" 其中之一,用于指定 Unicode 标准化形式。如果省略或为 undefined,则使用 "NFC"。
这些值具有以下含义:
"NFC":规范分解,然后进行规范组合;"NFD":规范分解;"NFKC":兼容分解,然后进行规范组合;"NFKD":兼容分解;
返回值
一个包含给定字符串的 Unicode 标准化形式的字符串。
示例
JavaScript
const name1 = '\u0041\u006d\u00e9\u006c\u0069\u0065';
const name2 = '\u0041\u006d\u0065\u0301\u006c\u0069\u0065';
console.log(`${name1}, ${name2}`);
// Expected output: "Amélie, Amélie"
console.log(name1 === name2);
// Expected output: false
console.log(name1.length === name2.length);
// Expected output: false
const name1NFC = name1.normalize('NFC');
const name2NFC = name2.normalize('NFC');
console.log(`${name1NFC}, ${name2NFC}`);
// Expected output: "Amélie, Amélie"
console.log(name1NFC === name2NFC);
// Expected output: true
console.log(name1NFC.length === name2NFC.length);
// Expected output: true1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2.29. toLocaleLowerCase([locales])
String 的 toLocaleLowerCase() 方法会根据特定区域设置的大小写映射规则,将字符串转换为小写形式并返回。
参数
locales一个带有 BCP 47 语言标签的字符串,或者是这种字符串的数组。指示要根据特定区域设置的大小写映射规则进行转换的区域设置。有关
locales参数的一般形式和解释,请参阅Intl主页上的参数描述。与使用
locales参数的其他方法不同,toLocaleLowerCase()不允许进行区域设置匹配。因此,在检查locales参数的有效性之后,toLocaleLowerCase()始终使用列表中的第一个区域设置(如果列表为空,则使用默认区域设置),即使该区域设置在实现中不受支持。
返回值
一个新的字符串,表示调用字符串根据特定区域设置的大小写映射规则转换得到的小写形式。
示例
JavaScript
const dotted = 'İstanbul';
console.log(`EN-US: ${dotted.toLocaleLowerCase('en-US')}`);
// Expected output: "i̇stanbul"
console.log(`TR: ${dotted.toLocaleLowerCase('tr')}`);
// Expected output: "istanbul"1
2
3
4
5
6
7
2
3
4
5
6
7
2.30. toLocaleUpperCase([locales])
String 的 toLocaleUpperCase() 方法会根据特定区域设置的大小写映射规则,将字符串转换为大写形式并返回。
参数
locales一个带有 BCP 47 语言标签的字符串,或者是这种字符串的数组。指示要根据特定区域设置的大小写映射规则进行转换的区域设置。有关
locales参数的一般形式和解释,请参阅Intl主页上的参数描述。与使用
locales参数的其他方法不同,toLocaleUpperCase()不允许进行区域设置匹配。因此,在检查locales参数的有效性之后,toLocaleUpperCase()始终使用列表中的第一个区域设置(如果列表为空,则使用默认区域设置),即使该区域设置在实现中不受支持。
返回值
一个新的字符串,表示调用字符串根据特定区域设置的大小写映射规则转换得到的大写形式。
示例
JavaScript
const city = 'istanbul';
console.log(city.toLocaleUpperCase('en-US'));
// Expected output: "ISTANBUL"
console.log(city.toLocaleUpperCase('TR'));
// Expected output: "İSTANBUL"1
2
3
4
5
6
7
2
3
4
5
6
7
2.31. toLowerCase()
String 的 toLowerCase() 方法将该字符串转换为小写形式。
返回值
一个新的字符串,表示转换为小写的调用字符串。
示例
JavaScript
const sentence = 'The quick brown fox jumps over the lazy dog.';
console.log(sentence.toLowerCase());
// Expected output: "the quick brown fox jumps over the lazy dog."1
2
3
4
2
3
4
2.32. toString()
String 的 toString() 方法返回该字符串的值。
返回值
表示指定字符串值的字符串。
示例
JavaScript
const stringObj = new String('foo');
console.log(stringObj);
// Expected output: String { "foo" }
console.log(stringObj.toString());
// Expected output: "foo"1
2
3
4
5
6
7
2
3
4
5
6
7
2.33. toUpperCase()
String 的 toUpperCase() 方法将该字符串转换为大写形式。
返回值
一个新的字符串,表示转换为大写的调用字符串。
示例
JavaScript
const sentence = 'The quick brown fox jumps over the lazy dog.';
console.log(sentence.toUpperCase());
// Expected output: "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG."1
2
3
4
2
3
4
2.34. valueOf()
valueOf() 方法返回 String 对象的字符串值。
返回值
一个字符串,表示给定 String 对象的原始值。
示例
JavaScript
const stringObj = new String('foo');
console.log(stringObj);
// Expected output: String { "foo" }
console.log(stringObj.valueOf());
// Expected output: "foo"1
2
3
4
5
6
7
2
3
4
5
6
7
2.36. 已弃用的方法
String.prototype.anchor()String.prototype.big()String.prototype.blink()String.prototype.bold()String.prototype.fixed()String.prototype.fontcolor()String.prototype.fontsize()String.prototype.italics()String.prototype.link()String.prototype.small()String.prototype.strike()String.prototype.sub()String.prototype.substr()String.prototype.sup()