One, the charAt ()

Returns the character at the specified position.

var str="abc"
console.log(str.charAt(0))//a
Copy the code

Second, the charCodeAt ()

Returns the Unicode encoding of the character at the specified position.

var str="abc"
 console.log(str.charCodeAt(1))//98
Copy the code

Third, concat ()

Connection string.

var a = "abc"; var b = "def"; var c = a.concat(b); console.log(c); //abcdefCopy the code

Four, indexOf ()

Retrieves the string. The indexOf() method is case-sensitive!

var str="Hello world!"
console.log(str.indexOf("Hello"))//0
console.log(str.indexOf("World"))//-1
console.log(str.indexOf("world"))///6
Copy the code

Five, the match ()

The match() method retrieves a specified value within a string or finds a match for one or more regular expressions. This method is similar to indexOf() and lastIndexOf(), but it returns the specified value rather than the position of the string.

var str="1 abc 2 def 3"
console.log(str.match(/\d+/g))//123
Copy the code

Sixth, the replace ()

The replace() method is used to replace some characters in a string with other characters, or to replace a substring that matches a regular expression.

var str="abc Def!"
console.log(str.replace(/abc/, "CBA"))//CBA Def!
Copy the code

Seven, the search ()

The search() method is used to retrieve a specified substring in a string, or to retrieve a substring that matches a regular expression. To perform a case-insensitive retrieval, append the flag I. If no matching substring is found, -1 is returned.

var str="abc DEF!"
console.log(str.search(/DEF/))//4
Copy the code

Eight, slice ()

Extracts a fragment of a string and returns the extracted portion in a new string. stringObject.slice(start,end); Start: The starting index of the fragment to be extracted. If it is negative, this parameter specifies the position from the end of the string. That is, -1 is the last character of the string, -2 is the second-to-last character, and so on. End: The subscript of the end of the fragment to be extracted next. If this parameter is not specified, the substring to be extracted includes the string from start to the end of the original string. If the argument is negative, it specifies the position from the end of the string.

var str="abc def ghk"
console.log(str.slice(6))//f ghk
Copy the code

Nine, the split ()

Splits a string into an array of strings.

var str="abc def ghi jkl"    
console.log(str.split(" "))//["abc", "def", "ghi", "jkl"]
console.log(str.split("") )//["a", "b", "c", " ", "d", "e", "f", " ", "g", "h", "i", " ", "j", "k", "l"]
console.log(str.split(" ",3))//["abc", "def", "ghi"]
Copy the code

Ten, toLocaleLowerCase ()

Converts a string to lowercase.

var str="ABC def!"
console.log(str.toLocaleLowerCase())//abc def!
Copy the code

Eleven, toLocaleUpperCase ()

Converts the string to uppercase.

var str="ABC def!"
console.log(str.toLocaleUpperCase())//ABC DEF!
Copy the code

Twelve, toLowerCase ()

Converts a string to lowercase.

var str="ABC def!"
console.log(str.toLowerCase())//abc def!
Copy the code

13, toUpperCase ()

Converts the string to uppercase.

var str="ABC def!"
console.log(str.toUpperCase())//ABC DEF!
Copy the code

14, substr ()

Extracts a specified number of characters from the initial index number in the string. StringObject. Substr (start, length). Start: required. The starting index of the substring to extract. It has to be a number. If it is negative, the argument declares the position from the end of the string. That is, -1 is the last character in the string, -2 is the second-to-last character, and so on. Length: Optional. Number of characters in a substring. It has to be a number. If this parameter is omitted, the string from the beginning of stringObject to the end is returned.

Var STR =" ABC def" console.log(str.substr(2))//c def console.log(str.substr(2,4))// cCopy the code

15 and the substring ()

Extracts the character between two specified index numbers in a string. StringObject. Substring (start, stop). Start: required. A non-negative integer specifying the position in stringObject of the first character of the substring to be extracted. Stop: Optional. A non-negative integer that is 1 more than the position in stringObject of the last character of the substring to be extracted. If omitted, the substring is returned up to the end of the string.

Var STR =" ABC def" console.log(str.substring(2))//c def console.log(str.substring(2))//c def console.log(str.substring(2,4))// cCopy the code

Similarity: If you write only one argument, they both work the same way: they both intercept the string fragment from the current subscript to the end of the string. substr(startIndex); substring(startIndex);

var str = '123456789'; console.log(str.substr(2)); // "3456789" console.log(str.substring(2)) ; / / "3456789"Copy the code

Difference: The second argument substr (startIndex,lenth) : The second argument is to truncate the length of the string (truncate a length of string from the starting point); Substring (startIndex, endIndex) : The second argument is to truncate the final index of the string (truncate the string between 2 positions, ‘head without tail’).

The console. The log (" 123456789 ". Substr (2, 5)); / / "34567" the console. The log (" 123456789 ". The substring (2, 5)); / / "345"Copy the code

ES6 new method for manipulating strings

A, codePointAt ()

Let s = '𠮷 a'; s.codePointAt(0) // 134071 s.codePointAt(1) // 57271 s.codePointAt(2) // 97Copy the code

The argument to the codePointAt method is the position of the character in the string (starting from 0). In the code above, JavaScript treats “𠮷a” as three characters, and codePointAt correctly recognizes “𠮷” on the first character, returning its decimal code point 134071 (that is, 20BB7 in hexadecimal). On the second character (the last two bytes of “𠮷”) and the third character “a”, the codePointAt method results in the same as the charCodeAt method.

Second, String. FromCodePoint ()

ES5 provides the String.fromCharcode method for returning corresponding characters from codepoints, but this method does not recognize 32-bit UTF-16 characters (Unicode numbers greater than 0xFFFF).

String. FromCharCode (0 x20bb7) / / "ஷ"Copy the code

In the above code, String.fromCharCode does not recognize points larger than 0xFFFF, so 0x20BB7 overruns, the highest bit 2 is discarded, and the character corresponding to the code point U+0BB7 is returned, not the character corresponding to the code point U+20BB7. ES6 provides the String.fromCodePoint method, which can recognize characters larger than 0xFFFF, to compensate for the string. fromCharCode method. In effect, it is opposite to codePointAt method.

String.fromCodePoint(0x20BB7) // "𠮷" string. fromCodePoint(0x78, 0x1F680, 0x79) === 'x\uD83D\uDE80y' // trueCopy the code

String traversal interface for of

for (let codePoint of 'abc') {
  console.log(codePoint)
}
// "a"
// "b"
// "c"
Copy the code

Besides traversing strings, the greatest advantage of this traverser is that it can recognize code points larger than 0xFFFF, which traditional for loops cannot recognize.

四, At ()

The AT method recognizes characters with a Unicode number greater than 0xFFFF and returns the correct character.

'ABC '. At (0)//"a". At (0)//"Copy the code

Five, the normalize ()

Many European languages have intonation and stress symbols. To represent them, Unicode provides two methods. One is to offer you something at once with an accent, like efforts (u01D1). The other is to offer synthetic character, the synthesis of original and accent characters, two characters into one, efforts at unifying efforts (u004F) and Alice (u030C).

These two representations, which are visually and semantically equivalent, are not recognized by JavaScript.

'\u01D1'==='\u004F\u030C' //false    
'\u01D1'.length // 1
'\u004F\u030C'.length // 2
Copy the code

The code above shows that JavaScript treats composite characters as two characters, causing the two representations to be unequal. ES6 provides a normalize() method for string instances to unify different representations of characters into the same form, called Unicode normalization.

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

Includes (), startsWith(), endsWith()

Traditionally, JavaScript has only had the indexOf method, which can be used to determine whether one string is contained within another. ES6 offers three new approaches.

**includes()** : Returns a Boolean value indicating whether the parameter string was found. **startsWith()** : Returns a Boolean value indicating whether the argument string is at the head of the original string. **endsWith()** : Returns a Boolean value indicating whether the argument string is at the end of the original string. let s = 'Hello world! '; s.startsWith('Hello') // true s.endsWith('! ') // true s.includes('o') // trueCopy the code

All three of these methods support a second parameter indicating where the search begins.

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

The code above shows that with the second argument n, endsWith behaves differently from the other two methods. It works for the first n characters, while the other two work from the NTH position up to the end of the string.

Seven, repeat ()

The repeat method returns a new string, repeating the original string n times.

'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""
Copy the code

The argument is rounded if it is a decimal.

'na'. Repeat (2.9) / / "nana"Copy the code

If the repeat argument is negative or Infinity, an error is reported.

'na'.repeat(Infinity)
// RangeError
'na'.repeat(-1)
// RangeError
Copy the code

PadStart (), padEnd()

ES2017 introduces the function of string completion length. If a string is not of a specified length, the header or tail is completed. PadStart () is used for head completion and padEnd() for tail completion.

'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'

'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'
Copy the code

In the code above, padStart and padEnd take two arguments, the first to specify the minimum length of the string, and the second to complete the string. Returns the original string if the length of the original string is equal to or greater than the specified minimum length.

'xxx'.padStart(2, 'ab') // 'xxx'
'xxx'.padEnd(2, 'ab') // 'xxx'
Copy the code

If the sum of the length of the completion string and the original string exceeds the specified minimum length, the completion string exceeding the number of bits is truncated.

'abc'.padStart(10, '0123456789')
// '0123456abc'
Copy the code

If the second argument is omitted, Spaces are used to complete the length by default.

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

A common use of padStart is to specify bits for numeric completion. The following code generates a 10-digit numeric string.

'1'.padStart(10, '0') // "0000000001"
'12'.padStart(10, '0') // "0000000012"
'123456'.padStart(10, '0') // "0000123456"
Copy the code

Another use is the 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

Nine, matchAll ()

The matchAll method returns a regular expression for all matches in the current string.

String template

Template strings are enhanced strings, identified by backquotes (‘). It can be used as a regular string, it can be used to define multi-line strings, or it can be used to embed variables in strings. —– string template, used more in the work.

// Ordinary string 'In JavaScript '\n' is a line-feed.' // Multi-line string 'In JavaScript this is not legal.' console.log(' string text line 1 string text line 2`); // Let name = "Bob", time = "today"; `Hello ${name}, how are you ${time}? `Copy the code

The template strings in the above code are represented by backquotes. If you need to use backquotes in a template string, it is preceded by backslash escape.

let greeting = ``Yo` World! `;Copy the code

If a template string is used to represent a multi-line string, all whitespace and indentation are preserved in the output.

$('#list').html(`
<ul>
  <li>first</li>
  <li>second</li>
</ul>
`);
Copy the code

In the above code, all whitespace and newlines for template strings are reserved, for example

    The tag is preceded by a line break. If you don’t want this newline, you can eliminate it using the trim method.

$('#list').html(`
<ul>
  <li>first</li>
  <li>second</li>
</ul>
`.trim());
Copy the code

A variable is embedded in the template string. You need to write the variable name in ${}.

function authorize(user, action) { if (! User.hasprivilege (action)) {throw new Error(// 'user' // + user.name // + 'is not authorized to do' // + action // + '.' `User ${user.name} is not authorized to do ${action}.`); }}Copy the code

You can put any JavaScript expression inside curly braces, perform operations, and reference object properties.

let x = 1;
let y = 2;

`${x} + ${y} = ${x + y}`
// "1 + 2 = 3"

`${x} + ${y * 2} = ${x + y * 2}`
// "1 + 4 = 5"

let obj = {x: 1, y: 2};
`${obj.x + obj.y}`
// "3"
Copy the code

You can also call functions from a template string.

function fn() {
  return "Hello World";
}    
`foo ${fn()} bar`
// foo Hello World bar
Copy the code

If the value in braces is not a string, it is converted to a string according to the usual rules. For example, if the braces are an object, the toString method of the object will be called by default. An error is reported if variables in the template string are not declared.

// let MSG = 'Hello, ${place}'; / / an errorCopy the code

Because inside the braces of the template string is executing JavaScript code, if the braces are a string, it will be printed as is.

`Hello ${'World'}`
// "Hello World"
Copy the code

Template strings can even be nested.

const tmpl = addrs => `
  <table>
  ${addrs.map(addr => `
    <tr><td>${addr.first}</td></tr>
    <tr><td>${addr.last}</td></tr>
  `).join('')}
  </table>
`;
Copy the code

PS: The content of ES6 in this article is mainly from Ruan Yifeng’s INTRODUCTION to ES6 Standards.