ES6 Chapter 4 new methods of string

Keywords: Javascript Front-end ECMAScript

preface

This chapter introduces new methods for string objects. Don't take important notes for less commonly used methods.
Link to the original text 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
Method nameReturn valuedescribeSecond parameter: Num
includes()Boolean valueDoes a string contain a parameter stringFrom the Num position to the end of the string
startsWith()Boolean valueWhether the beginning of a string contains a parameter stringFrom the Num position to the end of the string
endsWith()Boolean valueWhether the end of a string contains a parameter stringRepresents the first Num characters
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

// Use the second parameter
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()

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

parameterhandle
decimalRound down
character stringConvert to numbers first
negativereport errors
Infinityreport errors
const SAMPLE = 'Ha';
let sample1 = SAMPLE.repeat(4); // Repeat four times
console.log(sample1); // HaHaHaHa

let sample2 = SAMPLE.repeat(1.8); // The parameter is a small book, rounded down
console.log(sample2); // Ha

let sample3 = SAMPLE.repeat('3'); // The parameter is a string
console.log(sample3); // HaHaHa

let sample4 = SAMPLE.repeat(-4); // Parameter is negative
console.log(sample4); // Direct error reporting 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 padStart() and padEnd() accept two parameters

  • 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 trimStart() and trimEnd() methods to string instances. The whitespace character of the destination string, whose behavior is consistent with trim(). Whitespace characters include: space, tab, line feed and other whitespace characters.

trim() eliminates whitespace at the beginning and end of a string.
trimStart() eliminates the whitespace in the string header. The alias is: trimLeft();
trimEnd() eliminates whitespace at the end of a string. Alias: trimlight();
The return value is a new string representing the call string with spaces removed.

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

matchAll()

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

const string = 'sample1sample2sample3';
const regex = /sample/g;

for (const match of string.matchAll(regex)) {
  console.log(match);
}
// Traversal output
/*
['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.

// grammar
String.prototype.replaceAll(searchValue, replacement);

The replaceAll() method returns a new string. All parts of the new string that meet the pattern have been replaced by 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 $.
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 raw() method for native String objects. Is used to obtain the original String of a template String. In most cases, String.raw() is used to process template strings.

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

String.fromCodePoint()

The String.fromCodePoint() static method returns a string created using the specified sequence of code points. It can recognize characters larger than 0xFFFF, which makes up for the deficiency of String.fromCharCode() method.

console.log(String.fromCodePoint(9731, 9733, 9842, 0x2F804));
// Direct output ☃ ★ you

Posted by pspeakman on Thu, 25 Nov 2021 19:21:47 -0800