String
-
The escape sequence represents one character, so only one character counts.
let str="hello\nworld"; console.log(str.length); / / 11 Copy the code
-
Strings in ECMAScript are immutable; once created, their values cannot be changed. To change a string value in a variable, you must destroy the original string and then assign a new string.
let str = "abc"; str[0] = 'A'; console.log(str); //abc str = "Abc"; console.log(str); //Abc Copy the code
String conversion
-
Calls the toString() method of the value. Null and undefined do not have this method.
-
Use the String() transformation function
- The toString() method is called if there is one.
- If the value is null, “null” is returned.
- If the value is undefined, return “undefined”.
Template literals
-
Enclose the string with backquotes above the TAB key.
-
It will keep the space inside.
-
Interpolate with ${}.
let a = 1, b = 2; let str = `${a}+${b}=${a + b}`; console.log(str) / / 1 + 2 = 3 Copy the code
-
All inserted values are converted to strings using toString().
let person = { name: 'wn'.age: 18.toString() { return this.name + this.age; }}let str = `info:${person}`; console.log(str); //wn18 Copy the code
-
HTML string concatenation provides great convenience.
let person = { name: 'wn'.age: 18 } let str = `<p><span>${person.name}</span>:<span>${person.age}</span></p>`; document.write(str); Copy the code
-
You can insert the value before itself.
let str='abc'; str=`${str}abc`; str=`${str}abc`; console.log(str); //abcabcabc Copy the code
Raw string
- through
String.raw()
The tag functionGets the raw string.
console.log('\u00A9');
console.log(String.raw`\u00A9`);
/ / ©
//\u00A9
Copy the code