ES6 第四章 字符串的新增方法(ES6 Chapter 4 new methods of string)

前言

本章介绍字符串对象的新增方法。不常用的方法不做重点笔记。
本章原文链接:字符串的新增方法

includes()、startsWith()、endsWith()

确定一个字符串是否包含在另一个字符串中。ES6 又提供了三种新方法。

  • includes() 方法用于判断一个字符串是否包含在另一个字符串中
  • startsWith() 方法用来判断当前字符串是否以另外一个给定的子字符串开头
  • endsWith() 方法用来判断当前字符串是否是以另外一个给定的子字符串“结尾”的
方法名 返回值 描述 第二个参数 : Num
includes() 布尔值 一个字符串是否包含参数字符串 从第 Num 个位置直到字符串结束
startsWith() 布尔值 一个字符串的开头是否包含参数字符串 从第 Num 个位置直到字符串结束
endsWith() 布尔值 一个字符串的结尾是否包含参数字符串 表示前 Num 个字符
let sampleString = 'Hello world!';

const sample1 = sampleString.includes('llo');
const sample2 = sampleString.startsWith('H');
const sample3 = sampleString.endsWith('d!');
console.log(sample1, sample2, sample3); // true true true

// 使用第二个参数
const sample11 = sampleString.includes('llo', 1);
const sample12 = sampleString.startsWith('H', 1);
const sample13 = sampleString.endsWith('d!', 10);
console.log(sample11, sample12, sample13); // true false false

repeat()

方法返回一个新字符串,表示将原字符串重复次。
参数为小数就会向下取整,为负数和无穷()则会报错.

repeat()
n
Infinity
参数 处理
小数 向下取整
字符串 先转换成数字
负数 报错
Infinity 报错
const SAMPLE = 'Ha';
let sample1 = SAMPLE.repeat(4); // 重复四次
console.log(sample1); // HaHaHaHa

let sample2 = SAMPLE.repeat(1.8); // 参数为小书,向下取整
console.log(sample2); // Ha

let sample3 = SAMPLE.repeat('3'); // 参数为字符串
console.log(sample3); // HaHaHa

let sample4 = SAMPLE.repeat(-4); // 参数为负数
console.log(sample4); // 直接报错 Invalid count value

padStart(),padEnd()

ES2017 引入了字符串补全长度的功能。如果某个字符串不够指定长度,会在头部或尾部补全。

  • padStart()用于头部补全。
  • padEnd()用于尾部补全。

与都接受两个参数

padStart()
padEnd()
  • 参数一:字符串补全生效的最大长度。如果当前字符串小于指定的长度,则进行补全。
  • 参数二:用来补全的字符串。如果字符串长度过长,则会删除后面的多出的字符串。默认空格补全。
const SAMPLE = '368';

let newSample = SAMPLE.padStart(11, "000,");
let newSample1 = SAMPLE.padEnd(11, ",000");
console.log(newSample); // 000,000,368
console.log(newSample1); // 368,000,000

trimStart(),trimEnd()

ES2019 对字符串实例新增了和这两个方法。去处字符串的空白符,它们的行为与一致,空白符包括:空格、制表符 tab、换行符等其他空白符等。

trimStart()
trimEnd()
trim()

消除字符串的头尾空白符。
消除字符串头部的空白符,别名为:;
消除字符串尾部的空白符。别名为:;
返回值为一个新字符串,表示除去空格的调用字符串。

trim()
trimStart()
trimLeft()
trimEnd()
trimRight()
const SAMPLE = '  Ha  ';
let newSample = SAMPLE.trimStart();
let newSample1 = SAMPLE.trimEnd();
console.log(newSample); // Ha  
console.log(newSample1); //   Ha

matchAll()

方法返回一个包含所有匹配正则表达式的结果,返回的是一个迭代器(Iterator)。
这块不深入,后面正则表达式扩展再进行详解。

matchAll()
const string = 'sample1sample2sample3';
const regex = /sample/g;

for (const match of string.matchAll(regex)) {
  console.log(match);
}
// 遍历输出
/*
['sample', index: 0, input: 'sample1sample2sample3', groups: undefined]
['sample', index: 7, input: 'sample1sample2sample3', groups: undefined]
['sample', index: 14, input: 'sample1sample2sample3', groups: undefined]
*/

replaceAll()

简单来说,可以一次性替换所有匹配。

// 语法
String.prototype.replaceAll(searchValue, replacement);

方法返回一个新字符串,新字符串所有满足 的部分都已被 替换

replaceAll() 
pattern
replacement

两个参数

  • 参数一: 可以是一个字符串,也可以是一个全局的正则表达式(带有g修饰符)。
  • 参数二:第二个参数replacement是一个字符串,表示替换的文本,其中可以使用一些特殊字符串。除了为字符串,也可以是一个函数,该函数的返回值将替换掉第一个参数searchValue匹配的文本。

    $&:匹配的字符串。
    $ `:匹配结果前面的文本。
    $’:匹配结果后面的文本。
    $n:匹配成功的第n组内容,n是从1开始的自然数。这个参数生效的前提是,第一个参数必须是正则表达式。
    $$:指代美元符号$。

  • $&:匹配的字符串。
  • $ `:匹配结果前面的文本。
  • $’:匹配结果后面的文本。
  • $n:匹配成功的第n组内容,n是从1开始的自然数。这个参数生效的前提是,第一个参数必须是正则表达式。
  • $$:指代美元符号$。
const SAMPLE = 'HaHa,huhu,hehe';
let sample1 = SAMPLE.replaceAll('h', 'H');
let sample2 = SAMPLE.replaceAll('H', () => 'h');
console.log(sample1); // HaHa,HuHu,HeHe
console.log(sample2); // haha,huhu,hehe

String.raw()

ES6 还为原生的 对象,提供了一个方法。是用来获取一个模板字符串的原始字符串的,在大多数情况下, 是用来处理模版字符串的。

String
raw()
String.raw()
console.log(`Hi\n${2+3}!`); // 
/*
输出
Hi
5!
*/
console.log( String.raw`Hi\n${2+3}!`); // 输出 Hi\n5!

String.fromCodePoint()

静态方法返回使用指定的代码点序列创建的字符串。可以识别大于的字符,弥补了方法的不足。

String.fromCodePoint() 
0xFFFF
String.fromCharCode()
console.log(String.fromCodePoint(9731, 9733, 9842, 0x2F804));
// 直接输出 ★你
————————

preface

This chapter introduces new methods for string objects. Don’t take important notes for less commonly used methods.
Original link of this chapter: new method of string

includes()、startsWith()、endsWith()

Determines whether one string is contained in another. ES6 provides three new methods.

  • The includes () method is used to determine whether one string is contained in another string
  • The startswith () method is used to determine whether the current string starts with another given substring
  • The endswith() method is used to determine whether the current string ends with another given substring
方法名 返回值 描述 第二个参数 : Num
includes() 布尔值 一个字符串是否包含参数字符串 从第 Num 个位置直到字符串结束
startsWith() 布尔值 一个字符串的开头是否包含参数字符串 从第 Num 个位置直到字符串结束
endsWith() 布尔值 一个字符串的结尾是否包含参数字符串 表示前 Num 个字符
let sampleString = 'Hello world!';

const sample1 = sampleString.includes('llo');
const sample2 = sampleString.startsWith('H');
const sample3 = sampleString.endsWith('d!');
console.log(sample1, sample2, sample3); // true true true

// 使用第二个参数
const sample11 = sampleString.includes('llo', 1);
const sample12 = sampleString.startsWith('H', 1);
const sample13 = sampleString.endsWith('d!', 10);
console.log(sample11, sample12, sample13); // true false false

repeat()

Method returns a new string indicating that the original string is repeated several times.
If the parameter is decimal, it will be rounded down, and if it is negative and infinite (), an error will be reported

repeat()
n
Infinity
参数 处理
小数 向下取整
字符串 先转换成数字
负数 报错
Infinity 报错
const SAMPLE = 'Ha';
let sample1 = SAMPLE.repeat(4); // 重复四次
console.log(sample1); // HaHaHaHa

let sample2 = SAMPLE.repeat(1.8); // 参数为小书,向下取整
console.log(sample2); // Ha

let sample3 = SAMPLE.repeat('3'); // 参数为字符串
console.log(sample3); // HaHaHa

let sample4 = SAMPLE.repeat(-4); // 参数为负数
console.log(sample4); // 直接报错 Invalid count value

padStart(),padEnd()

Es2017 introduces the function of string completion length. If a string is not long enough, it will be completed at the head or tail.

  • Padstart() is used for head completion.
  • Padend() is used for tail completion.

Both and accept two parameters

padStart()
padEnd()
  • Parameter 1: the maximum length of string completion. If the current string is less than the specified length, it is completed.
  • Parameter 2: the string used to complete. If the string length is too long, the subsequent extra strings will be deleted. Default space completion.
const SAMPLE = '368';

let newSample = SAMPLE.padStart(11, "000,");
let newSample1 = SAMPLE.padEnd(11, ",000");
console.log(newSample); // 000,000,368
console.log(newSample1); // 368,000,000

trimStart(),trimEnd()

Es2019 adds and these two methods to string instances. The blank characters of the destination string have the same behavior as. The blank characters include: < strong > spaces, tabs, line breaks, etc. < / strong > other blank characters, etc.

trimStart()
trimEnd()
trim()

Eliminate whitespace at the beginning and end of a string.
Eliminate the blank character in the string header, and the alias is:;
Eliminate whitespace at the end of the string. Alias:;
The return value is a new string representing the call string with spaces removed.

trim()
trimStart()
trimLeft()
trimEnd()
trimRight()
const SAMPLE = '  Ha  ';
let newSample = SAMPLE.trimStart();
let newSample1 = SAMPLE.trimEnd();
console.log(newSample); // Ha  
console.log(newSample1); //   Ha

matchAll()

Method returns a result containing all matching regular expressions, and returns an iterator.
This is not in-depth, and the regular expression extension will be explained in detail later.

matchAll()
const string = 'sample1sample2sample3';
const regex = /sample/g;

for (const match of string.matchAll(regex)) {
  console.log(match);
}
// 遍历输出
/*
['sample', index: 0, input: 'sample1sample2sample3', groups: undefined]
['sample', index: 7, input: 'sample1sample2sample3', groups: undefined]
['sample', index: 14, input: 'sample1sample2sample3', groups: undefined]
*/

replaceAll()

Simply put, you can replace all matches at once.

// 语法
String.prototype.replaceAll(searchValue, replacement);

Method returns a new string. All satisfied parts of the new string have been replaced

replaceAll() 
pattern
replacement

Two parameters

  • Parameter 1: it can be a string or a global regular expression (with G modifier).
  • Parameter 2: the second parameter replacement is a string, which represents the replaced text. Some special strings can be used. In addition to being a string, it can also be a function whose return value will replace the text matching the first parameter SearchValue.
    $&: matching string.
    $`: matches the text in front of the result.
    $’: matches the text after the result.
    $n: the nth group of content matched successfully. N is a natural number starting from 1. The precondition for this parameter to take effect is that the first parameter must be a regular expression.
    $$: refers to the dollar sign $.
  • $&: matching string.
  • $`: matches the text in front of the result.
  • $’: matches the text after the result.
  • $n: the nth group of content matched successfully. N is a natural number starting from 1. The precondition for this parameter to take effect is that the first parameter must be a regular expression.
  • $$: refers to the dollar sign $.
const SAMPLE = 'HaHa,huhu,hehe';
let sample1 = SAMPLE.replaceAll('h', 'H');
let sample2 = SAMPLE.replaceAll('H', () => 'h');
console.log(sample1); // HaHa,HuHu,HeHe
console.log(sample2); // haha,huhu,hehe

String.raw()

ES6 also provides a method for native objects. It is used to obtain the original string of a template string. In most cases, it is used to process the template string.

String
raw()
String.raw()
console.log(`Hi\n${2+3}!`); // 
/*
输出
Hi
5!
*/
console.log( String.raw`Hi\n${2+3}!`); // 输出 Hi\n5!

String.fromCodePoint()

The static method returns a string created using the specified sequence of code points. It can recognize characters larger than, which makes up for the deficiency of the method.

String.fromCodePoint() 
0xFFFF
String.fromCharCode()
console.log(String.fromCodePoint(9731, 9733, 9842, 0x2F804));
// 直接输出 ★你