前端技术学习路线图-初阶-JavaScript-字符串方法
字符串方法
String.prototype@@iterator
[@@iterator]()
方法返回一个新的 Iterator 对象,它遍历字符串的代码点,返回每一个代码点的字符串值。
const str = 'The quick red fox jumped over the lazy dog\'s back.';
const iterator = str[Symbol.iterator]();
let theChar = iterator.next();
while (!theChar.done && theChar.value !== ' ') {
console.log(theChar.value);
theChar = iterator.next();
// Expected output: "T"
// "h"
// "e"
}
String.prototype.at()
at()
方法接受一个整数值,并返回一个新的 String
,该字符串由位于指定偏移量处的单个 UTF-16 码元组成。该方法允许正整数和负整数。负整数从字符串中的最后一个字符开始倒数。
const sentence = 'The quick brown fox jumps over the lazy dog.';
let index = 5;
console.log(`Using an index of ${index} the character returned is ${sentence.at(index)}`);
// Expected output: "Using an index of 5 the character returned is u"
index = -4;
console.log(`Using an index of ${index} the character returned is ${sentence.at(index)}`);
// Expected output: "Using an index of -4 the character returned is d"
String.prototype.charAt()
charAt()
方法从一个字符串中返回指定的字符。
var anyString = "Brave new world";
console.log("The character at index 0 is '" + anyString.charAt(0) + "'");
// The character at index 0 is 'B'
console.log("The character at index 1 is '" + anyString.charAt(1) + "'");
// The character at index 1 is 'r'
console.log("The character at index 2 is '" + anyString.charAt(2) + "'");
// The character at index 2 is 'a'
console.log("The character at index 3 is '" + anyString.charAt(3) + "'");
// The character at index 3 is 'v'
console.log("The character at index 4 is '" + anyString.charAt(4) + "'");
// The character at index 4 is 'e'
console.log("The character at index 999 is '" + anyString.charAt(999) + "'");
// The character at index 999 is ''
String.prototype.charCodeAt()
charCodeAt()
方法返回 0
到 65535
之间的整数,表示给定索引处的 UTF-16 代码单元。
字符串中的字符从左向右索引,第一个字符的索引值为 0,最后一个字符(假设该字符位于字符串 stringName 中)的索引值为 stringName.length - 1
。如果指定的 index 值超出了该范围,则返回一个空字符串。
const sentence = 'The quick brown fox jumps over the lazy dog.';
const index = 4;
console.log(`The character code ${sentence.charCodeAt(index)} is equal to ${sentence.charAt(index)}`);
// Expected output: "The character code 113 is equal to q"
String.prototype.codePointAt()
codePointAt()
方法返回 一个 Unicode 编码点值的非负整数。
如果在指定的位置没有元素则返回 undefined。如果在索引处开始没有 UTF-16 代理对,将直接返回在那个索引处的编码单元。
Surrogate Pair 是 UTF-16 中用于扩展字符而使用的编码方式,是一种采用四个字节 (两个 UTF-16 编码) 来表示一个字符,称作代理对。
'ABC'.codePointAt(1); // 66
'\uD800\uDC00'.codePointAt(0); // 65536
'XYZ'.codePointAt(42); // undefined
String.prototype.concat()
concat()
方法将一个或多个字符串与原字符串连接合并,形成一个新的字符串并返回。
concat
方法将一个或多个字符串与原字符串连接合并,形成一个新的字符串并返回。 concat
方法并不影响原字符串。
如果参数不是字符串类型,它们在连接之前将会被转换成字符串。
let hello = 'Hello, '
console.log(hello.concat('Kevin', '. Have a nice day.'))
// Hello, Kevin. Have a nice day.
let greetList = ['Hello', ' ', 'Venkat', '!']
"".concat(...greetList) // "Hello Venkat!"
"".concat({}) // [object Object]
"".concat([]) // ""
"".concat(null) // "null"
"".concat(true) // "true"
"".concat(4, 5) // "45"
String.prototype.endsWith()
endsWith()
方法用来判断当前字符串是否是以另外一个给定的子字符串“结尾”的,根据判断结果返回 true
或 false
。
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: false
String.fromCharCode()
静态 String.fromCharCode()
方法返回由指定的 UTF-16 代码单元序列创建的字符串。
console.log(String.fromCharCode(189, 43, 190, 61));
// Expected output: "½+¾="
String.fromCodePoint()
String.fromCodePoint()
静态方法返回使用指定的代码点序列创建的字符串。
console.log(String.fromCodePoint(9731, 9733, 9842, 0x2F804));
// Expected output: "☃★♲你"
String.prototype.includes()
includes()
方法执行区分大小写的搜索,以确定是否可以在另一个字符串中找到一个字符串,并根据情况返回 true
或 false
。
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"
String.prototype.indexOf()
indexOf()
方法,给定一个参数:要搜索的子字符串,搜索整个调用字符串,并返回指定子字符串第一次出现的索引。给定第二个参数:一个数字,该方法将返回指定子字符串在大于或等于指定数字的索引处的第一次出现。
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
const searchTerm = 'dog';
const indexOfFirst = paragraph.indexOf(searchTerm);
console.log(`The index of the first "${searchTerm}" from the beginning is ${indexOfFirst}`);
// Expected output: "The index of the first "dog" from the beginning is 40"
console.log(`The index of the 2nd "${searchTerm}" is ${paragraph.indexOf(searchTerm, (indexOfFirst + 1))}`);
// Expected output: "The index of the 2nd "dog" is 52"
String.prototype.isWellFormed()
String
值的 isWellFormed()
方法返回一个表示该字符串是否包含单独的代理项的布尔值。
JavaScript 中的字符串是 UTF-16 编码的。UTF-16 编码中有代理对的概念,这一概念在 UTF-16 字符、Unicode 码位和字素簇(grapheme clusters)部分有详细介绍。
isWellFormed() 让你能够测试一个字符串是否是格式正确的(即不包含单独的代理项)。由于引擎能够直接访问字符串的内部表示,与自定义实现相比 isWellFormed() 更高效。如果你需要将字符串转换为格式正确的字符串,可以使用 toWellFormed() 方法。isWellFormed() 让你可以对格式正确和格式错误的字符串进行不同的处理,比如抛出一个错误或将其标记为无效。
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.lastIndexOf()
lastIndexOf()
方法返回调用 String
对象的指定值最后一次出现的索引,在一个字符串中的指定位置 fromIndex
处从后向前搜索。如果没找到这个特定值则返回 -1。
该方法将从尾到头地检索字符串 str,看它是否含有子串 searchValue。开始检索的位置在字符串的 fromIndex 处或字符串的结尾(没有指定 fromIndex 时)。如果找到一个 searchValue,则返回 searchValue 的第一个字符在 str 中的位置。str中的字符位置是从 0 开始的。
'canal'.lastIndexOf('a'); // returns 3(没有指明 fromIndex 则从末尾 l 处开始反向检索到的第一个 a 出现在 l 的后面,即 index 为 3 的位置)
'canal'.lastIndexOf('a', 2); // returns 1(指明 fromIndex 为 2 则从 n 处反向向回检索到其后面就是 a,即 index 为 1 的位置)
'canal'.lastIndexOf('a', 0); // returns -1(指明 fromIndex 为 0 则从 c 处向左回向检索 a 发现没有,故返回 -1)
'canal'.lastIndexOf('x'); // returns -1
'canal'.lastIndexOf('c', -5); // returns 0(指明 fromIndex 为 -5 则视同 0,从 c 处向左回向查找发现自己就是,故返回 0)
'canal'.lastIndexOf('c', 0); // returns 0(指明 fromIndex 为 0 则从 c 处向左回向查找 c 发现自己就是,故返回自己的索引 0)
'canal'.lastIndexOf(''); // returns 5
'canal'.lastIndexOf('', 2); // returns 2
String.prototype.localeCompare()
localeCompare()
方法返回一个数字来指示一个参考字符串是否在排序顺序之前、之后或与给定字符串相同。
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: 0
String.prototype.match()
match()
方法检索返回一个字符串匹配正则表达式的结果。
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"]
String.prototype.matchAll()
matchAll()
方法返回一个包含所有匹配正则表达式的结果及分组捕获组的迭代器。
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"]
String.prototype.normalize()
normalize()
方法会按照指定的一种 Unicode 正规形式将当前字符串规范化。(如果该值不是字符串,则首先将其转换为一个字符串)。
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: true
String.prototype.padEnd()
padEnd()
方法会用一个字符串填充当前字符串(如果需要的话则重复填充),返回填充后达到指定长度的字符串。从当前字符串的末尾(右侧)开始填充。
const str1 = 'Breaded Mushrooms';
console.log(str1.padEnd(25, '.'));
// Expected output: "Breaded Mushrooms........"
const str2 = '200';
console.log(str2.padEnd(5));
// Expected output: "200 "
String.prototype.padStart()
padStart()
方法用另一个字符串填充当前字符串(如果需要的话,会重复多次),以便产生的字符串达到给定的长度。从当前字符串的左侧开始填充。
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"
String.raw()
String.raw()
是一个模板字符串的标签函数,它的作用类似于 Python 中的字符串前缀 r 和 C# 中的字符串前缀 @(还是有点区别的,详见隔壁 Chromium 那边的这个 issue),是用来获取一个模板字符串的原始字符串的,比如说,占位符(例如 ${foo})会被处理为它所代表的其他字符串,而转义字符(例如 \n)不会。
在大多数情况下,String.raw() 是用来处理模版字符串的。不要被上面复杂的参数要求吓到,因为像所有的 tag functions一样,你通常不需要把它看成一个普通函数,你只需要把它放在模板字符串前面就可以了,而不是在它后面加个括号和一堆参数来调用它,引擎会替你去调用它。
String.raw() 是唯一一个内置的模板字符串标签函数,因为它太常用了。不过它并没有什么特殊能力,你自己也可以实现一个和它功能一模一样的标签函数。
String.raw`Hi\n${2+3}!`;
// 'Hi\\n5!',Hi 后面的字符不是换行符,\ 和 n 是两个不同的字符
String.raw `Hi\u000A!`;
// "Hi\\u000A!",同上,这里得到的会是 \、u、0、0、0、A 6 个字符,
// 任何类型的转义形式都会失效,保留原样输出,不信你试试.length
let name = "Bob";
String.raw `Hi\n${name}!`;
// "Hi\nBob!",内插表达式还可以正常运行
// 正常情况下,你也许不需要将 String.raw() 当作函数调用。
// 但是为了模拟 `t${0}e${1}s${2}t` 你可以这样做:
String.raw({ raw: 'test' }, 0, 1, 2); // 't0e1s2t'
// 注意这个测试,传入一个 string,和一个类似数组的对象
// 下面这个函数和 `foo${2 + 3}bar${'Java' + 'Script'}baz` 是相等的。
String.raw({
raw: ['foo', 'bar', 'baz']
}, 2 + 3, 'Java' + 'Script'); // 'foo5barJavaScriptbaz'
String.prototype.repeat()
repeat()
构造并返回一个新字符串,该字符串包含被连接在一起的指定数量的字符串的副本。
"abc".repeat(-1) // RangeError: repeat count must be positive and less than inifinity
"abc".repeat(0) // ""
"abc".repeat(1) // "abc"
"abc".repeat(2) // "abcabc"
"abc".repeat(3.5) // "abcabcabc" 参数 count 将会被自动转换成整数。
"abc".repeat(1/0) // RangeError: repeat count must be positive and less than inifinity
({toString : () => "abc", repeat : String.prototype.repeat}).repeat(2)
//"abcabc",repeat 是一个通用方法,也就是它的调用者可以不是一个字符串对象。
String.prototype.replace()
replace()
方法返回一个由替换值(replacement
)替换部分或所有的模式(pattern
)匹配项后的新字符串。模式可以是一个字符串或者一个正则表达式,替换值可以是一个字符串或者一个每次匹配都要调用的回调函数。如果pattern
是字符串,则仅替换第一个匹配项。
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
console.log(p.replace('dog', 'monkey'));
// Expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"
const regex = /Dog/i;
console.log(p.replace(regex, 'ferret'));
// Expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"
String.prototype.replaceAll()
replaceAll()
方法返回一个新字符串,新字符串所有满足 pattern
的部分都已被replacement
替换。pattern
可以是一个字符串或一个 RegExp
, replacement
可以是一个字符串或一个在每次匹配被调用的函数。
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
console.log(p.replaceAll('dog', 'monkey'));
// Expected output: "The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?"
// Global flag required when calling replaceAll with regex
const regex = /Dog/ig;
console.log(p.replaceAll(regex, 'ferret'));
// Expected output: "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"
String.prototype.search()
search()
方法执行正则表达式和 String
对象之间的一个搜索匹配。
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
// Any character that is not a word character or whitespace
const regex = /[^\w\s]/g;
console.log(paragraph.search(regex));
// Expected output: 43
console.log(paragraph[paragraph.search(regex)]);
// Expected output: "."
String.prototype.slice()
slice()
方法提取某个字符串的一部分,并返回一个新的字符串,且不会改动原字符串。
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"
String.prototype.split()
split()
方法使用指定的分隔符字符串将一个String
对象分割成子字符串数组,以一个指定的分割字串来决定每个拆分的位置。
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."]
String.prototype.startsWith()
startsWith()
方法用来判断当前字符串是否以另外一个给定的子字符串开头,并根据判断结果返回 true
或 false
。
const str1 = 'Saturday night plans';
console.log(str1.startsWith('Sat'));
// Expected output: true
console.log(str1.startsWith('Sat', 3));
// Expected output: false
String.prototype.substring()
substring()
方法返回一个字符串在开始索引到结束索引之间的一个子集,或从开始索引直到字符串的末尾的一个子集。
substring 提取从 indexStart 到 indexEnd(不包括)之间的字符。特别地:
- 如果 indexStart 等于 indexEnd,substring 返回一个空字符串。
- 如果省略 indexEnd,substring 提取字符一直到字符串末尾。
- 如果任一参数小于 0 或为 NaN,则被当作 0。
- 如果任一参数大于 stringName.length,则被当作 stringName.length。
- 如果 indexStart 大于 indexEnd,则 substring 的执行效果就像两个参数调换了一样。
var anyString = "Mozilla";
// 输出 "Moz"
console.log(anyString.substring(0,3));
console.log(anyString.substring(3,0));
console.log(anyString.substring(3,-3));
console.log(anyString.substring(3,NaN));
console.log(anyString.substring(-2,3));
console.log(anyString.substring(NaN,3));
// 输出 "lla"
console.log(anyString.substring(4,7));
console.log(anyString.substring(7,4));
// 输出 ""
console.log(anyString.substring(4,4));
// 输出 "Mozill"
console.log(anyString.substring(0,6));
// 输出 "Mozilla"
console.log(anyString.substring(0,7));
console.log(anyString.substring(0,10));
String.prototype.toLocaleLowerCase()
toLocaleLowerCase()
方法根据任何指定区域语言环境设置的大小写映射,返回调用字符串被转换为小写的格式。
toLocaleLowerCase() 方法返回根据任意区域语言大小写映射集而转换成小写格式的字符串。
toLocaleLowerCase() 并不会影响字符串原本的值。在大多数情况下,该方法和调用 toLowerCase()的结果相同,但是在某些区域环境中,比如土耳其语,它的大小写映射并不遵循在 Unicode 中的默认的大小写映射,因此会有一个不同的结果。
'ALPHABET'.toLocaleLowerCase(); // 'alphabet'
'\u0130'.toLocaleLowerCase('tr') === 'i'; // true
'\u0130'.toLocaleLowerCase('en-US') === 'i'; // false
let locales = ['tr', 'TR', 'tr-TR', 'tr-u-co-search', 'tr-x-turkish'];
'\u0130'.toLocaleLowerCase(locales) === 'i'; // true
String.prototype.toLocaleUpperCase()
toLocaleUpperCase()
方法根据本地主机语言环境把字符串转换为大写格式,并返回转换后的字符串。
const city = 'istanbul';
console.log(city.toLocaleUpperCase('en-US'));
// Expected output: "ISTANBUL"
console.log(city.toLocaleUpperCase('TR'));
// Expected output: "İSTANBUL"
String.prototype.toLowerCase()
toLowerCase()
会将调用该方法的字符串值转为小写形式,并返回。
toLowerCase
会将调用该方法的字符串值转为小写形式,并返回。toLowerCase
不会影响字符串本身的值。
console.log('中文简体 zh-CN || zh-Hans'.toLowerCase());
// 中文简体 zh-cn || zh-hans
console.log( "ALPHABET".toLowerCase() );
// "alphabet"
String.prototype.toString()
字符串对象的 toString()
方法返回一个字符串,表示指定的字符串。
const stringObj = new String('foo');
console.log(stringObj);
// Expected output: String { "foo" }
console.log(stringObj.toString());
// Expected output: "foo"
String.prototype.toUpperCase()
toUpperCase()
方法将调用该方法的字符串转为大写形式并返回(如果调用该方法的值不是字符串类型会被强制转换)。
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."
String.prototype.toWellFormed()
String 值的 toWellFormed()
方法返回一个新字符串,原字符串中所有单独的代理项在新字符串中会被替换为 Unicode 替换字符 U+FFFD。
JavaScript 中的字符串是 UTF-16 编码的。UTF-16 编码中有代理对的概念,这一概念在 UTF-16 字符、Unicode 码位和字素簇(grapheme clusters)部分有详细介绍。
toWellFormed() 迭代字符串的码元,并将任何单独的代理项替换为 Unicode 替换字符 U+FFFD �。这确保了返回的字符串格式正确并可用于期望正确格式字符串的函数,比如 encodeURI。由于引擎能够直接访问字符串的内部表示,与自定义实现相比 toWellFormed() 更高效。
当在某些上下文中使用格式不正确的字符串时,例如 TextEncoder,它们会自动转换为使用相同替换字符的格式正确的字符串。当单独的代理项被呈现时,它们也会呈现为替换字符(一个带有问号的钻石形状)。
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"
String.prototype.trim()
trim()
方法从字符串的两端清除空格,返回一个新的字符串,而不修改原始字符串。此上下文中的空格是指所有的空白字符(空格、tab、不换行空格等)以及所有行终止符字符(如 LF、CR 等)。
const greeting = ' Hello world! ';
console.log(greeting);
// Expected output: " Hello world! ";
console.log(greeting.trim());
// Expected output: "Hello world!";
String.prototype.trimEnd()
trimEnd()
方法会删除字符串末尾的空白字符。trimRight()
是这个方法的别名。
const greeting = ' Hello world! ';
console.log(greeting);
// Expected output: " Hello world! ";
console.log(greeting.trimEnd());
// Expected output: " Hello world!";
String.prototype.trimStart()
trimStart()
方法会删除字符串开头的空白字符。trimLeft()
是此方法的别名。
const greeting = ' Hello world! ';
console.log(greeting);
// Expected output: " Hello world! ";
console.log(greeting.trimStart());
// Expected output: "Hello world! ";
String.prototype.valueOf()
valueOf()
方法返回 String
对象的原始值。
const stringObj = new String('foo');
console.log(stringObj);
// Expected output: String { "foo" }
console.log(stringObj.valueOf());
// Expected output: "foo"