String对象方法(四)match/matchAll/normalize/padEnd/padStart

111 阅读1分钟

String对象方法match/matchAll/normalize/padEnd/padStart

match:通过正则表达式,将匹配出的内容存入数组并返回

var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var regexp = /[A-E]/gi;
var matches_array = str.match(regexp);
console.log(matches_array); 
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']

matchAll:通过正则表达式,将匹配出的内容存入数组,同时还会存储对应匹配的情况,最后返回

const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';
const array = [...str.matchAll(regexp)];
console.log(array[0]);
// ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', groups: undefined]
console.log(array[1]);
// ['test2', 'e', 'st2', '2', index: 5, input: 'test1test2', groups: undefined]

normalize:定的一种Unicode正规形式将当前字符串正规化

const name1 = '\u0041\u006d\u00e9\u006c\u0069\u0065';
const name2 = '\u0041\u006d\u0065\u0301\u006c\u0069\u0065';
console.log(name1, name2);
// Amélie Amélie
console.log(name1 === name2);
// false
console.log(name1.length === name2.length);
// false
const str1 = name1.normalize('NFD');
console.log(str1);
// Amélie

padStart:指定对应输出宽度,如果字符串小于该宽度,则用指定的字符从头部进行填充

let str = "hello world";
console.log(str.padStart(30, "*"));
// *******************hello world

padEnd:指定对应输出宽度,如果字符串小于该宽度,则用指定的字符从尾部进行填充

let str = "hello world";
console.log(str.padEnd(30, '*'));
// hello world*******************