I am small and live in Wuhan, do two years of new media, ready to use 6 months time to switch to the front end of the industry.

Lesson Objective for today

Yesterday, based on some page search, I learned the basic data type of ES basic concept in chapter 3 of JavaScirpt Advanced Programming (3rd edition). Yesterday, I actually saw that String has many methods and attributes, so today, I mainly study String data type carefully based on search. Is a day for learning, refueling, small and !!!!


Today’s Lesson summary

Learn string data types in detail from the following aspects

  • String definition
  • String properties
  • Soft approach to strings
  • Tough method for strings
  • Object general method
  • A prototype method for string literals
  • Summary of string methods

Today, XIAO again tried a different way of description. She spent a lot of time checking materials and sorting out several pages, hoping that everyone could accept ~~~~ and recommend a website. This is also the recommendation jsConsole ~~~~~ that I saw in MDN JS Shells today

Also due to the number of words, today’s article is divided into three uploaded ~~~~

  • The previous part includes (string definition, string properties, string soft methods part methods)
  • The midsection is to include (Soft method part method of string)
  • The next part includes (string soft method part method, string strong method and object general method, string literal prototype method, string method summary and today’s summary)

define

Base string

String literals (defined by single or double quotes) and strings that call the String method directly (without generating an instance of a String object through new) are basic strings. A primitive string is a string object method that has no related extension methods and can only be used once the primitive string has been converted to a string object. When the base string needs to call a method or query value that is unique to a string object, JavaScript automatically converts the base string to a string object and calls the corresponding method or executes a query.


String object

A constructor for a string or a sequence of characters. Strings are useful for holding data that can be represented as text. Some common string operations are querying string lengths, constructing and concatenating strings using the + and += operators, using indexOf to check the position of a subString within the parent string, or extracting substrings from the parent string using the subString method.


Template string

Template literals /Template literals are string literals that allow expressions to be embedded. You can use multi-line strings and string interpolation. They were called template strings in previous versions of the ES2015 specification. Template strings use backquotes () instead of double and single quotes in regular strings. Template strings can contain placeholders for a particular syntax (${expression}). Placeholders in the expression with the surrounding text will pass to a default function, this function is responsible for all the parts together, if a template string begins by expression, then the string is called template string with labels, the expression is often a function, it will be called after the template string handling, before the output the final result, You can use this function to manipulate template strings. When using a backquote (‘) inside a template string, you need to precede it with an escape character (\).

` \ ` `= = ="`" // --> true
Copy the code


Noun a dictionary

Explanations of variable nouns appear in this article

var a = 4;
var b = 8;
var strString = "hello little";
var oo = new Object(a);var oString = new String("hello little");
var oBool = new Boolean(true);
var oNum = new Number(68);
var oArray = new Array("demo"."little"."you");
var oDate = new Date(a);
// d800-dbff utF-16 high-half zone of UTF-16
// dc00-dfff utF-16 low-half zone of UTF-16
var oString_1 = 'A \uD87E\uDC04 Z';
var tString_1 =`hello Template`;
var tString_2 =`hello line 1 hello line 2`;
// 'string text ${expression} string text' uses expressions in template strings
var tString_3 =`Fifteen is ${a + b} and\nnot The ${2 * a + b}. `;

function tag(strings, ... values) {
 //String stores a String that is not expression
 //values stores the computed value of expression
  console.log(strings[0]); // The value of "Hello "before the first expression
  console.log(strings[1]); // The value of "little" before the second expression
  console.log(strings[2]); // The value of "hahaha" before the third expression
  console.log(strings[3]); // "" value after the third expression
  console.log(values[0]);  // 12 The first expression value
  console.log(values[1]);  // 32 Second expression value
  console.log(values[2]); // 0.5 third expression value

  return "Hello, everyone, I am small and big!";
}

console.log(strString);//hello little
console.log(oString);//[String: 'hello little']
console.log(oString_1);//A you Z middle characters that are not in BMP will display garbled characters
console.log(tString_1);//hello Template
// Print it out in the original format such as newline and indent
console.log(tString_2);//hello Template line 1 \n \t hello Template line 2
// tag(tString_1); //h e l l undefined undefined undefined
// tag(tString_2); //h e l l undefined undefined undefined
// tag(tString_3); //F i f t undefined undefined undefined
console.log(tString_3);//Fifteen is 12 and \n not 16.
 //tag 'string text ${expression} string text' uses the tag method in template strings // Will not print until console is called. //tString_4 is the return value of the tag function. var tString_4 = tag`Hello ${ a + b } little ${ a * b}hahaha ${ a / b}`; Copy the code





The following is mainly, according to personal understanding of the definition of general variable noun dictionary ~~~

The variable name meaning For example,
objectName Name of the associated object type As the abovejsIn the codeString
varName The instantiated variable name of the associated object type As the abovejsIn the codestrString.oString.tString_1
varName_val The actual content of the related object type after instantiation As the abovejsIn the codehello little
functionName The name of the function Like abovetag
BMP Basic Multilingual Plane, also known as Plane 0 or Plane 0, isUnicodeA coding section in. Code fromU+0000toU+FFFF. The current version is revised 10.0.0 and was published on June 20, 2017. No, for example,
ES5 ECMAScript version 5, published as ECMAScript 2015, was originally released in December 2009 as the first version, and was later extensively revised in June 2015 No, for example,
ES6 ECMAScript Sixth edition (published as ECMAScript 2016), 2016 No, for example,
ES7 ECMAScript seventh edition (published as ECMAScript 2017), released in 2017 No, for example,
letter The letter Letter (8) stands for eight letters and each letter is one in length
char Chinese characters Char (8) represents eight Chinese characters, each of which is one in length
num digital Num (8) represents eight digits, each of which is one in length
sign symbol Sign (8) represents eight symbols, each of which is one in length
\s Spaces \s(8) represents eight Spaces, each of which is one length
\t The indentation operator \t(8) represents eight indents, one of which is four in length
\n A newline \n(8) represents eight newlines, each of which is of one length
\u A newline \u(8) represents eight non-BMP characters, one of which is two characters in length
param1,param2,param3,… ,paramN We need to pass in the values of the first to the NTH arguments As the abovejsIn the codehello little
Soft method Does not change the original string value Is that after executing a method,varNameThe original contents will not change
Tough way Changes the original string value Is that after executing a method,varNameThe original contents will change
The parent string The original object content As the abovejsIn the codestrString.oString.tString_1
The substring Pass in the parameter values that you want to retrieve or replace As the abovejsIn the codehello little
Accept negative parameter The function takes a negative parameter and returns the corresponding value as normal If these five words appear in the description of the method, it means that the method accepts negative parameters. If they do not appear, it means that the method does not accept negative parameters
Not recommended This feature is non-standard, so try not to use it in production. If these five words appear in the following property and method descriptions, they mean that it is best not to use this property or method.
Have been abandoned None of the major browsers currently support it If this word appears in the description of the property or method, you will get an error or return undefined.
In the test Some browsers are still developing this feature, please refer to the browser compatibility table to see which prefixes are appropriate for different browsers. The syntax and behavior of this feature may change in future versions of browsers as the standard documentation for this feature may be revised. If you use a property or method that is not compatible with all browsers, it is best not to use this property or method.

String properties

Inherits the properties of an object

The property name describe Method of use
constructor A reference (pointer) to the function that created the object. varName.constructor
__proto__ Objects have properties__proto__The implicit stereotype of an object points to the stereotype of the constructor that constructed the object. varName.__proto__

Inherit the properties of funciton

The property name describe Method of use
arguments Not recommendedThe attribute represents the argument to the function passed in. It is an array-like object. Deprecated for many years now, the recommended practice is to use what is available inside the functionargumentsObject to access the arguments to the function. When a function is called recursively (the same function is run multiple times at the same time, with multiple sets of arguments), thenargumentsProperty is the argument passed in the last call to this function. If the function is not executing, the value ofargumentsThe value of the property isnull. objectName.arguments or functionName.arguments
caller Not recommendedIf a functionfunctionNameIs in theGlobal scopeIs called within, thenfunctionName.callerfornullIf, on the other hand, a function is called within the scope of another functionfunctionName.callerRefers to the one that called itThe function, the common form of the propertyarguments.callee.callerTo replace the abandonedarguments.caller. objectName.caller or functionName.caller
displayName Not recommendedGets the display name of the function. objectName.displayName or functionName.displayName
length Length is an attribute value of the function object. Length is the number of parameters that must be passed to the function. The number of parameters does not include the number of remaining parameters, only the number of parameters before the first one has a default value. In contrast, arguments.length is the number of actual arguments passed when the function is called. objectName.length or functionName.length
name Returns the name of a function declaration, usednew Function(...)Syntax-created functions or justFunction(...)The Create Function object and its name areanonymous. objectName.name or functionName.name
prototype Function objects have properties__proto__The implicit stereotype of an object points to the stereotype of the constructor that constructed the object. objectName.prototype or functionName.prototype

Common attribute values for strings

constructor

The variable name Way to be obtained Attribute values
strString strString.constructor [Function: String]
oString oString.constructor [Function: String]
oString_1 oString_1.constructor [Function: String]
tString_1 tString_1.constructor [Function: String]
tString_2 tString_2.constructor [Function: String]
tString_3 tString_3.constructor [Function: String]
tString_4 tString_4.constructor [Function: String]


proto

The variable name Way to be obtained Attribute values
strString strString.__proto__ [String: ”]
oString oString.__proto__ [String: ”]
oString_1 oString_1.__proto__ [String: ”]
tString_1 tString_1.__proto__ [String: ”]
tString_2 tString_2.__proto__ [String: ”]
tString_3 tString_3.__proto__ [String: ”]
tString_4 tString_4.__proto__ [String: ”]


length

The variable name Way to be obtained Attribute values explain
strString strString.length 12 letter(11)+\s(1)
oString oString.length 12 letter(11)+\s(1)
oString_1 oString_1.length 6 letter(2)+\s(2)+\u(1)
tString_1 tString_1.length 14 letter(13)+\s(1)
tString_2 tString_2.length 26 letter(18)+num(2)+\s(5)+\n(1)
tString_3 tString_3.length 25 letter(15)+num(4)+\s(4)+sign(1)+\n(1)
tString_4 tString_4.length 10 char(9)+sign(1)


Matters needing attention

Character name Whether it can be modified
writable false
enumerable false
configurable false

prompt

All instances of String inherit from String.prototype. Any changes to String.prototype will affect all String instances.

Note, however, that because each varName has a different constructor, the result is different when instanceof is used to test whether an object has a constructor’s Prototype property in its prototype chain.

// How to use it
object instanceof constructor
or object instanceof(constructor// @param1 object Specifies the object to be detected. // @param2constructorA constructor //instanceof operator is used to checkconstructorPrototype Whether the prototype chain of the parameter Object exists.Copy the code
The variable name Way to be obtained Attribute values
strString strString instanceof(String) false
oString oString instanceof(String) true
tString_1 tString_1 instanceof(String) false
tString_2 tString_2 instanceof(String) false
tString_3 tString_3 instanceof(String) false
tString_4 tString_4 instanceof(String) false


Soft method for string objects

HTML related methods

An overview of the

The method name describe parameter
big() Not recommended, the string is displayed in large font, only in the page will have two large font size effect. There is no
small() Not recommended, the string is displayed as a small font, and the effect of two small fonts is only visible on the page. There is no
blink() Not recommendedTo display the string flashing string, currently not seen with browser support There is no
bold() Not recommended, the string displayed in bold string, only in the page will have bold effect, IE is not compatible. There is no
italics() Not recommendedTo italicize the string, which only works on the page. There is no
strike() Not recommended, displays the string as a strikeout string, which only works on the page. There is no
fixed() Not recommended, which displays the string as typewriter text, only works on the page. There is no
sub() Not recommended, displays the string as a subscript, which only works on the page. There is no
sup() Not recommended, displays the string as a superscript, which only works on the page. There is no
anchor(anchorname) Not recommendedTo createHTMLThe anchor. Outputs a string as a uniquely identified pureaTags are only effective on the page. @param anchorName Required, defines a name for the anchor. If no arguments are passed, one is printednameProperties forundefinedtheaThe label.
link(url) Not recommendedTo display the string as a link, which only works on the page. If no argument is passed, an href attribute is outputundefinedThe A tag of. @param URL Required, specifies the URL to link to.
fontcolor(color) Not recommendedReturns a string of the specified color. It only works on the page and if no arguments are passed in, it prints onecolorProperties forundefinedFont tag. @param color Required. Specify font color for strings. The value must be a color name (red), RGB value (RGB (255,0,0)), or hexadecimal number (#FF0000).
fontsize(size) Not recommendedReturns a string of the specified font size. It only works on the page. If no arguments are passed, one is printedsizeProperties forundefinedthefontThe label. The @param size argument must be a number from 1 to 7. The larger the number, the larger the font.

Detailed methods

1) big()

Method of use The results of
varName.big() <big>varName_val</big>

2) small()

Method of use The results of
varName.small() <small>varName_val</small>

3) blink()

Method of use The results of
varName.blink() <blink>varName_val</blink>

4) bold()

Method of use The results of
varName.bold() <b>varName_val</b>

5) italics()

Method of use The results of
varName.italics() <i>varName_val</i>

6) strike()

Method of use The results of
varName.strike() <strike>varName_val</strike>

7) fixed()

Method of use The results of
varName.fixed() <tt>varName_val</tt>

8) sub()

Method of use The results of
varName.sub() <sub>varName_val</sub>

9) sup()

Method of use The results of
varName.sup() <sup>varName_val</sup>

10) anchor(anchorname)

Method of use The results of
varName.anchor(param1) <a name="param1">varName_val</a>

11) link(url)

Method of use The results of
varName.link(param1) <a href="param1">varName_val</a>

12) fontcolor(color)

Method of use The results of
varName.fontcolor(param1) <font color="param1">varName_val</font>

13) fontsize(size)

Method of use The results of
varName.fontsize(param1) <font size="param1">varName_val</font>

Coding related

An overview of the

The method name describe parameter
charAt(index) Returns a character at a specific position, the first character with no argument, and the specified cursor character with a cursor value @param index is not required, a positive integer between 0 and the string length minus 1. (0~ varname.length-1), if it is not a value, the default value is 0.
charCodeAt(index) Returns an integer between 0 and 65535 representing the value at the given indexUTF-16Code units (inUnicodeThe coding unit represents a singleUTF-16In the case of coding units,UTF-16Coding unit matchingUnicodeCoding unit. But in — for exampleUnicodeCoding unit0x10000This kind of — can’t be aUTF-16If the coding unit is represented separately, it can only be matchedUnicodeThe first coding unit of the proxy pair). @param index An integer greater than or equal to 0 and less than the length of the string. (0~ varname.length-1), if it is not a value, the default value is 0.
codePointAt(pos) In the test, returns a non-negative integer using utF-16 encoding for the value at the given position. @param pos The position of the element in the string to transcode.
normalize([form]) In the testReturns the Unicode normalized form of the value of the calling string. @param form One of the four Unicode normal forms “NFC”, “NFD”, “NFKC”, and “NFKD”. The default value is “NFC”.
fromCharCode(num1, … , numN) Return a String instead of a String object. Since fromCharCode is a static method of String, you should use string.fromCharcode () like this, not as a method of the String you’re creating. @param num1, … NumN A sequence of numbers representing Unicode values.
FromCodePoint (num1,… , numN) Not recommended, returns a string created using Unicode encoding, and if passed an invalid Unicode encoding, a RangeError will be raised (for example, “RangeError: NaN is not a valid code point”). @param num1, … NumN A sequence of numbers representing Unicode values.

Detailed methods

1) charAt(index)

Characters in a string are indexed from left to right, with the index value of the first character being 0 and the index value of the last character (assuming it is in the string varName) being varname.length-1. If the specified index value is outside the range, an empty string is returned. And no matter how many arguments you pass in, this method only processes the value of the first argument you pass in. If you pass in a decimal, this method rounds up. For example, if you pass in a value of 1.2, this method thinks you pass in a value of 2. Note, however, that this method can only detect characters in a print containing a basic multilingual plane (BMP), and if the string contains something not in the BMP, the print will be garbled.

Method of use The results of
oString.charAt() h
oString.charAt(oString.length-1) e

The wrong sample

Method of use The results of
OString. CharAt (1.2) e
OString. CharAt (1, 2, 3) e
oString.charAt(-2) An empty string
oString.charAt(oString) h
oString.charAt(true) e
oString.charAt(false) h
oString.charAt(null) h
oString.charAt(undefined) h
oString.charAt(NaN) h
oString.charAt(oo) h
oString.charAt(oNum) An empty string
oString.charAt(oArray) h
oString.charAt(oDate) An empty string
oString.charAt(oString.length) An empty string





2) charCodeAt()

Unicode code points range from 0 to 1,114,111 (0x10FFFF). The leading 128 Unicode encoding units are the same as the ASCII character encoding. For more information about Unicode, see the JavaScript Guide. Note that charCodeAt always returns a value less than 65,536. This is because a higher code point is represented by a pair of “pseudo-characters” for Lower Encoding, which constitute a real character. Therefore, in order to view or reproduce the full character of 65536 or more encoding characters, we need to obtain the value of charCodeAt(I +1) as well as the value of charCodeAt(I) (just like looking at /reproducing a two-character string). Alternatively, get the value of codePointAt(I) instead. CharCodeAt returns NaN if the specified index is less than 0 or not less than the length of the string. And no matter how many arguments you pass in, this method only processes the value of the first argument you pass in. If you pass in a decimal, this method rounds up. For example, if you pass in a value of 1.2, this method thinks you pass in a value of 2. The return value is a number representing the utF-16 code unit value of the character at the given index (index index in varName); If the index is out of range, NaN is returned. If you want the value of the entire code point, use codePointAt(). Backward compatibility: In historical versions (such as JavaScript 1.2), charCodeAt returns a number representing the ISO-Latin-1 encoded value of the character at a given index. The ISO-Latin-1 codeset ranges from 0 to 255. The beginning 0 through 127 matches the ASCII character set directly.

Method of use The results of
oString.charCodeAt() 104
oString.charCodeAt(oString.length-1) 101

The wrong sample

Method of use The results of
OString. CharCodeAt (1.2) 101
OString. CharCodeAt (1, 2, 3) 101
oString.charCodeAt(-2) NaN
oString.charCodeAt(oString) 104
oString.charCodeAt(true) 101
oString.charCodeAt(false) 104
oString.charCodeAt(null) 104
oString.charCodeAt(undefined) 104
oString.charCodeAt(NaN) 104
oString.charCodeAt(oo) 104
oString.charCodeAt(oNum) NaN
oString.charCodeAt(oArray) 104
oString.charCodeAt(oDate) NaN
oString.charCodeAt(oString.length) NaN


Commonly used encoding table

character Corresponding Unicode value
\t(horizontal TAB) 9
\n(newline character) 10
\ s (space) 32
! (Exclamation mark) 33
34
# 35
$ 36
% 37
& 38
39
( 40
) 41
* 42
+ 43
. 44
45
(Full stop) 46
/ 47
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
: 58
; 59
< 60
= 61
> 62
? 63
@ 64
A 65
Z 90
[ 91
| 92
] 93
^ 94
_ 95
` 96
a 97
z 122
{ 123
(Middle vertical line) 124
} 125
~ 126

3) codePointAt(pos)

The return value is the number represented in the encoding unit of the given index in the string, or undefined if the specified index is less than 0 or not less than the length of the string. If, codePointAt returns undefined. And no matter how many arguments you pass in, this method only processes the value of the first argument you pass in. If you pass in a decimal, this method rounds up. For example, if you pass in a value of 1.2, this method thinks you pass in a value of 2. If there are no UTF-16 proxy pairs to start with at the index, the encoding unit at that index is returned directly. CodePointAt () can be thought of as a more complete version of charCodeAt(), because the two methods execute the same for all characters in BMP, and may differ only if non-BMP code point effects are passed. CodePointAt () returns the full code point for non-BMP, even if the code point contains multiple code units, but charCodeAt() returns only the first code unit at position pos. Surrogate Pair is a utF-16 encoding method used to extend characters. It uses four bytes (two UTF-16 encodings) to represent a character. Note, however, that codePointAt() is not supported in Safari since it was first introduced in ES5, and is only supported in newer versions of other browsers.

Method of use The results of
oString.codePointAt() 104
oString.codePointAt(oString.length-1) 101

The wrong sample

Method of use The results of
OString. CodePointAt (1.2) 101
OString. CodePointAt (1, 2, 3) 104
oString.codePointAt(-2) undefined
oString.codePointAt(oString) 104
oString.codePointAt(true) 101
oString.codePointAt(false) 104
oString.codePointAt(null) 104
oString.codePointAt(undefined) 104
oString.codePointAt(NaN) 104
oString.codePointAt(oo) 104
oString.codePointAt(oNum) undefined
oString.codePointAt(oArray) 104
oString.codePointAt(oDate) undefined
oString.codePointAt(oString.length) undefined


4) normalize([form])

Parameters of the abbreviations Parameter name Chinese Meaning of parameters
NFC Normalization Form Canonical Composition Canonical form canonical composition
NFD Normalization Form Canonical Decomposition Canonical form normalizes decomposition
NFKC Normalization Form Compatibility Composition Normalized form compatibility composition
NFKD Normalization Form Compatibility Decomposition Normalized form compatibility decomposition

warning

If the form is passed an invalid parameter value, RangeError will be raised directly. The exploratory form should be one of NFC, NFD, NFKC, NFKD. It will not be processed by itself. It is a very cool method. And this has nothing to do with normalize() in the DOM method, so don’t get confused. If you don’t have anything in your string that isn’t BMP, then you don’t need to use this method. The varName_val of varName is returned unchanged. So far, my main test sample has no intuitive feeling after using this method. If I meet different effects later, I will supplement it.

Method of use The results of
varName.normalize() varName_val
varName.normalize(“NFC”) varName_val
varName.normalize(“NFD”) varName_val
varName.normalize(“NFKC”) varName_val
varName.normalize(“NFKD”) varName_val


5) fromCharCode (num1,… , numN)

Although most commonly used Unicode values can be represented by a 16-bit number (as in the early days of JavaScript standardization), And fromCharCode() returns a character for most values (that is, ucS-2 values are a subset of UTF-16 for most characters), but in order to handle all Unicode values (up to 21 bits), fromCharCode() alone is not sufficient. Because a high-encoding character is a single character formed by two lower-value representations, string.fromCodePoint () (part of the ES6 draft) is used to return such a pair of lower-encoding characters that it is possible to fully represent these high-encoding characters. If you pass in a decimal, this method rounds up. For example, if you pass in a value of 1.2, this method assumes that you passed in a value of 2. When you pass no arguments or some unrecognized argument, the method returns an empty string.

Method of use The results of
objectName.fromCharCode(65) A

The wrong sample

Method of use The results of
objectName.fromCharCode() An empty string
The objectName. FromCharCode (65.2) A
Thirdly, objectName. FromCharCode (65.8, 66 ABC
objectName.fromCharCode(-2) An empty string
objectName.fromCharCode(oString) An empty string
objectName.fromCharCode(true) The statement
objectName.fromCharCode(false) An empty string
objectName.fromCharCode(null) An empty string
objectName.fromCharCode(undefined) An empty string
objectName.fromCharCode(NaN) An empty string
objectName.fromCharCode(oo) An empty string
objectName.fromCharCode(oNum) D
objectName.fromCharCode(oArray) An empty string
objectName.fromCharCode(oDate) The statement




  1. FromCodePoint (num1,… , numN)

Because fromCodePoint() is a static method of String, it can only be used with string.fromcodePoint (), not directly on the String instance you’re creating. Quite the fromCharCode() upgrade, more inclusive in handling non-BMP content, but stricter in passing parameters.


warning

If an invalid Unicode encoding is passed in, a RangeError will be raised (e.g. RangeError: NaN is not a valid code point). Such as decimal, scientific count, undefined, negative, string, array, timestamp, etc., if passed these values, the method will directly error, will not execute the following, will not handle itself, is a very cold method oh!

Method of use The results of
objectName.fromCodePoint(65) A
objectName.fromCodePoint() An empty string
objectName.fromCodePoint(oNum) D
objectName.fromCodePoint(true) The statement
objectName.fromCodePoint(false) The statement
objectName.fromCodePoint(null) The statement

The wrong sample

Method of use The results of
The objectName. FromCodePoint (65.2) RangeError
Thirdly, objectName. FromCodePoint (65.8, 66 RangeError
objectName.fromCodePoint(-2) RangeError
objectName.fromCodePoint(oString) RangeError
objectName.fromCodePoint(undefined) RangeError
objectName.fromCodePoint(NaN) RangeError
objectName.fromCodePoint(oo) RangeError
objectName.fromCodePoint(oArray) RangeError
objectName.fromCodePoint(oDate) RangeError



This article is formatted using MDNICE