“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”

1. String.fromCodePoint()

The first thing to mention is that string.fromCharCode (), both methods are used to convert Unicode code to the corresponding text. But string.fromCodePoint () is an improvement over String.fromCharCode().

The method name Js version The difference between
formCharCode es5 Code points greater than 0xFFFF are not recognized and overflow occurs. FromCodePoint is the opposite
formCodePoint es6 When multiple arguments are passed, they are returned as a string; fromCharCode is not
// Validates 1:0x20bb7 > 0xFFFF
String.fromCharCode(0x20BB7);    / / "ஷ"
String.fromCodePoint(0x20BB7);   / / "𠮷"
String.fromCodePoint(0xFFFF);    / / ""
String.fromCharCode(0xFFFF);    / / ""

// Verify 2: whether multiple arguments are combined into one string
String.fromCodePoint(0x78.0x1f680.0x79) = = ='x\uD83D\uDE80y'     // true
String.fromCharCode(0x78.0x1f680.0x79) = = ='x\uD83D\uDE80y'      // false

Copy the code

2. String.raw()

Two uses:

  • One is for template strings, which should not be used with ()
  • Another is to use (callSite… Substitutions), two parameters: callSite is a template string calling object, should be an object with raw property {raw: [‘foo’, ‘bar’, ‘baz’]}

2.1 String. Raw ` `

Precedes the escape character with a slash

String.raw`Hi\nThe ${2+3}`\ \"Hi\\5"
String.raw`Hi\u000A! `\ \"Hi\\u000A!"
Copy the code

If the slash of the original string has been escaped (\n)

String.raw`Hi\\n`; \ \"Hi\\\\n"
String.raw`Hi\\n`= ="Hi\\\\n"; \ \true

Copy the code

2.2 String. Raw (callSite,… substitutions)

Normally, this method is rarely used, but to simulate t${0}e${1}s${2}t

String.raw({raw:'test'},3.4.5)   // "t3e4s5t"

String.raw({raw: ['aa'.'bb'.'cc'].1+2.3})    // "aa3bb3cc"

/ / the following functions and ` aa ${2 + 3} bb ${' Java '+' Script '} cc ` is equal.
String.raw({raw: ['aa'.'bb'.'cc']},2+3.'java'+'Script')  // aa5bbjavaScriptcc
Copy the code

2.3 String.raw() code implementation

String.raw = function (strings, ... values) {
  let output = ' ';
  let index;
  for (index = 0; index < values.length; index++) {
    output += strings.raw[index] + values[index];
  }

  output += strings.raw[index]
  return output;
}
Copy the code

3. Example method: codePointAt()

3.1 Instance method, static method, prototype method

First of all, let me tell you what an instance method is. Maybe I’m a chicken, so I don’t know what an instance method is when I hear it. Js method types are: instance method, static method, prototype method three.

  • Instance methods

Instance methods are defined using the Prototype property of the function object. The object can be used only after it is instantiated

function A (){}
A.prototype.sayHello = function(){
	console.log("Hello")}var a = new A();
a.sayHello();     // Hello
Copy the code
  • A static method

It can be called only through the a. method

function A(){}
A.sayHello = function(){
	console.log("Hello")
}
A.sayHello();     //Hello
Copy the code
  • Prototype method

Both method instances and constructors in the prototype are accessible

function A(){}
A.prototype.sayHello = function(){
	console.log("Prototype method")
}
A.sayHello = function(){
	console.log("Static method")
}
A.sayHello()     // "static method"
A.prototype.sayHello()     // "prototype method"
let a = new A();
a.sayHello();       // "prototype method"
Copy the code

A function is an object, and the prototype property in the function object can be thought of as a pointer to a method (so that you don’t have to recreate the method every time you create a new instance with the constructor). This makes sense. Var a is a reference to a, that is, a pointer to sayHello, and a.sayhello () is an error because a is not a pointer, and a.sayhello () is an error because a is not a method object.

CodePointAt () is designed to solve the problem of Unicode code points greater than 0xFFFF not being able to read the entire character

3.2 JavaScript character storage format

  • Inside javaScript, characters are stored in UTF-16 format.
  • Each character is fixed to 2 bytes.
  • For characters that require 4 bytes of storage (characters with a Unicode code point greater than 0xFFFF), javaScript considers them to be two characters.
  • The code point for the Chinese character “𠮷” (note that this character is not “ji” for “auspicious”) is 0x20BB7, the UTF-16 code is 0xD842 0xDFB7 (55362 57271 in decimal), and requires 4 bytes of storage
var s = "𠮷";
s.length  // 2 The string length is misjudged to be 2
// Returns a two-character decimal point
s.charCodeAt(0) / / 55362
s.charCodeAt(1) / / 57271

// Returns its decimal code point 134071 (i.e., hexadecimal 20BB7)
s.charPointAt(0)  / / 134071
s.charPointAt(1)  / / 57271
Copy the code

Converts decimal code points to hexadecimal

s.codePointAt(0).toString(16)      // "20bb7"
Copy the code

3.3 use

The codePointAt() method is the easiest way to test whether a character consists of two bytes or four bytes

function is32Bit(c) {
  return c.codePointAt(0) > 0xFFFF;
}
is32Bit("𠮷") // true
is32Bit("a") // false
Copy the code

Example method: normalize()

Many European languages have intonation symbols and stress symbols And Unicode provides two methods:

  • Provide an accented character directly, such as: efforts at decluttering (\u01D1)
  • Synthesis symbols, for example: O (\u004F) and Welles (\u030C) synthesis (\u004F\u030C)
'\u01D1'= = ='\u004F\u030C' //false
'\u01D1'.length / / 1
'\u004F\u030C'.length / / 2
Copy the code

The above code javaScript does not recognize that they are the same

4.1 Do not receive parameters

But the normalize() method emmealizes Unicode

'\u01D1'.normalize() === '\u004F\u030C'.normalize()     // true
Copy the code

4.2 Receiving Parameters

'\u004F\u030C'.normalize('NFC').length / / 1
'\u004F\u030C'.normalize('NFD').length / / 2
Copy the code

The above code indicates that the NFC parameter returns the synthesized form of the character, and the NFD parameter returns the decomposed form of the character.

However, the Normalize method currently does not recognize compositions of three or more characters. In this case, you can only use regular expressions and use Unicode numbering intervals.

Example methods: includes(), startsWith(), endsWith()

Use: To determine whether a string is contained in another string

  • JavaScript has an indexOf method
let a ="abcd";
a.indexOf("b");  / / 1
a.indexOf("e");  // -1
Copy the code
  • Includes () returns whether the Boolean value contains a character
a.includes("b");    // true
a.includes("f");    // false
Copy the code
  • StartsWith (). Returns a Boolean value indicating whether the argument string is at the head of the original string
let a = "abc";
a.startsWith("a");  // true
a.startsWith("b");	// false
Copy the code
  • EndsWith (): Returns a Boolean value indicating whether the argument string is at the end of the original string
a.endsWith("c");    // true
a.endsWith("a");    // false
Copy the code

StartsWith (), endsWith(), and includes() all have a second parameter that indicates the starting position for the search.

let s = 'Hello world! ';
s.startsWith('world'.6) // true
s.endsWith('Hello'.5) // true
s.includes('Hello'.6) // false
Copy the code

6. Instance method: repeat()

Function: Returns a new string, indicating that the original string is repeated several times

  • The normal repeat
"x".repeat(3);     // "xxx"
"hello".repeat(2);   // "hellohello"
Copy the code
  • 0
"x".repeat(0)    / / ""
Copy the code
  • Decimals are rounded down and you’re rounded down
"x".repeat(2.5).  // "xx"
Copy the code
  • Negative number or Infinity error
"x".repeat(-1)        // RangeError
"x".repeat(Infinity)  // RangeError
Copy the code
  • Negative numbers between 0 and negative 1. They’re all rounded to 0
"x".repeat(-0.3)         / / ""
Copy the code
  • NaN is equal to 0
"x".repeat(NaN)         / / ""
Copy the code
  • The string is converted to a number first
"x".repeat("2")    // "xx"    
Copy the code

Example methods: padStart(), padEnd()

7.1 role

Used to complete the string, and padStart() to complete the header. PadEnd () is used for tail completion.

Two parameters:

  • First: The maximum length for string completion to take effect
  • Second: the string used for completion

7.2 Passing two parameters

  • Normal completion
'xxx'.padStart(5."abc");   // "abxxx"
'xxx'.padEnd(5."abc");     // "xxxab"
Copy the code
  • If the length of the original string is greater than or = the maximum length (that is, the first parameter), the original string is returned
'xxx'.padStart(2.'ab')     // "xxx"
'xxx'.padEnd(2.'ab')       // "xxx"
Copy the code
  • The completion string is truncated if the length of the completion string is greater than the maximum length
'abc'.padStart(10.'0123456789')    // "0123456abc"
Copy the code

7.3 Omit the second parameter

Omit the second parameter and complete with Spaces by default

'x'.padStart(4) 	// ' x'
'x'.padEnd(4) 		// 'x '
Copy the code

7.4 use

  • Specifies bits for numeric completion
'1'.padStart(10.'0')       / / "0000000001"
'123456'.padStart(10.'0') / / "0000123456"
Copy the code
  • Prompt string format
'12'.padStart(10.'YYYY-MM-DD')   // "YYYY-MM-12"
'09-12'.padStart(10.'YYYY-MM-DD') // "YYYY-09-12"
Copy the code

Example methods: trimStart(), trimEnd()

  • TrimStart () removes whitespace from the string header
  • TrimEnd () removes whitespace at the end of the string
const s = ' abc ';

s.trim() // "abc"
s.trimStart() // "abc "
s.trimEnd() // " abc"
Copy the code

The browser also deploytwo additional methods, trimLeft() is an alias for trimStart(), and trimRight() is an alias for trimEnd(). These two uses are the same as trimStart() and trimEnd().

Example method: replaceAll()

9.1 the replace ()

Only the first match can be replaced

'aabbcc'.replace('b'.'_')    // aa_bcc
Copy the code

To replace all b’s, use the /g modifier

'aabbcc'.replace(/b/g.'_')    // 'aa__cc'
Copy the code

9.2 replaceAll ()

  • The first argument passes a string
'aabbcc'.replaceAll('b'.'_')         // "aa__cc"
Copy the code
  • The first argument passes the regular expression without the /g modifier replaceAll
/ / is not an error
'aabbcc'.replace(/b/.'_')

/ / an error
'aabbcc'.replaceAll(/b/.'_')
Copy the code
  • The second argument is a string that represents the replacement text, where some special strings can be used.
// $& indicates the matching string, which is' b 'itself
// So return the same as the original string
'abbc'.replaceAll('b'.'$&')
// 'abbc'

// $' indicates the string before the match result
// For the first 'b', $' refers to 'a'
// For the second 'b', $' refers to 'ab'
'abbc'.replaceAll('b'.'$`)
// 'aaabc'

// $' indicates the string after the match result
// For the first 'b', $' refers to 'BC'
// For the second 'b', $' refers to 'c'
'abbc'.replaceAll('b'.` $' `)
// 'abccc'

// $1 indicates the first group match of the regular expression and refers to 'ab'
// $2 indicates the second group match of the regular expression, which refers to 'BC'
'abbc'.replaceAll(/(ab)(bc)/g.'$2 $1')
// 'bcab'

// $$refers to $
'abc'.replaceAll('b'.'$$')
// 'a$c'
Copy the code
  • The second argument can be a function as well as a string
'aabbcc'.replaceAll('b'.() = > '_')   // 'aa__cc'
Copy the code