This is the 8th day of my participation in the August Text Challenge.More challenges in August

A template string

ES6 template strings are special strings that replace the original string concatenation function

1. Usage: Marked with back quotes

let name = 'seven';
let age = 18;

// Traditional string concatenation:
let str = 's name, + name + ', age: + age;
// The template string is written like this:
let str = ` name:${name}Age:${age}`;
Copy the code

The stitching effect is more obvious for UL:

// Line breaks must be concatenated with +
let ul = '<ul>' +
'<li>' + name + '</li>' + 
'<li>' + name + '</li>' + 
'</ul>'

// You can wrap lines at will
let ul = `<ul>
<li>${name}</li>
<li>${age}</li>
</ul>`
Copy the code

2. Tagged template strings (you can customize template rules)

Writing: Prefixes the original template string with a tag tag and implements the same method as the tag name

let name = 'seven';
let age = 18;
// the name of the fn tag can be defined arbitrarily, as long as it is used consistently
function fn(strings) {
  let args = Array.prototype.slice.call(arguments.1);
  let str = ' ';
  for (let i = 0; i < args.length; i++) {
    // To distinguish the default template strings, we enclose single quotes and parentheses around variables
    str += (strings[i] + ` ('${args[i]}') `);
  }
  str += strings[strings.length - 1]
  return str;
}

let str = fn` name:${name}Age:${age}At the age of `;
console.log(str); // Name (' Xiao Qi '), age ('18')
Copy the code

3. Implement a template string yourself

let name = 'seven';
let age = 18;
let str = 'name :(\'${name}\'), age :(\'${age}\') age'
str = str.replace(/\$\{([^}]*)\}/g.function () {
  return eval(arguments[1])});console.log(str); // name :(' xiao qi '), age :('18') old
Copy the code

2, string new method

1. String.raw()

ES6 provides a raw() method for native Strings. This method returns a string in which all slashes have been escaped (that is, a slash followed by another slash), often used in template string processing.

String.raw`Hi\nThe ${2 + 3}! `
// Actually returns "Hi\\n5!" , displays the escaped result "Hi\n5!"

String.raw`Hi\u000A! `;
// Actually returns "Hi\\u000A!" , displays the escaped result "Hi\u000A!"
Copy the code

If the slash of the original String has been escaped, string.raw () is escaped again.

String.raw`Hi\\n`
/ / return \ \ "Hi \ \ n"

String.raw`Hi\\n`= = ="Hi\\\\n" // true
Copy the code

String.raw() is essentially a normal function, just a label function dedicated to template strings. If written as a normal function, its first argument should be an object with a RAW attribute, and the RAW attribute value should be an array of parsed values for the template string.

// `foo${1 + 2}bar`
/ / is equivalent to
String.raw({ raw: ['foo'.'bar']},1 + 2) // "foo3bar"
Copy the code

In the above code, the first argument to the string.raw () method is an object whose RAW property is equivalent to the array parsed from the original template String.

As a function, the code for String.raw() is basically as follows.

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

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

Previously, JavaScript had only the indexOf method, which could be used to determine whether a string was contained in another string. Now, 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 str = 'Hello world! ';

str.startsWith('Hello') // true
str.endsWith('! ') // true
str.includes('o') // true
Copy the code

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

let str = 'Hello world! ';

str.startsWith('world'.6) // true
str.endsWith('Hello'.5) // true
str.includes('Hello'.6) // false
Copy 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.

3. Instance method: repeat()

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

'7'.repeat(3) / / "777"
'hello'.repeat(2) // "hellohello"
'777'.repeat(0) / / ""
Copy the code

The argument is rounded if it is a decimal.

'qi'.repeat(2.9) // "qiqi"
Copy the code

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

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

However, if the argument is a decimal between 0 and -1, it is the same as 0 because the round is performed first. If the decimal number between 0 and -1 is rounded to -0, repeat is regarded as 0.

'qi'.repeat(-0.9) / / ""
Copy the code

The NaN argument is equal to 0.

'qi'.repeat(NaN) / / ""
Copy the code

If the argument of the repeat is a string, it is converted to a number first.

'qi'.repeat('qi') / / ""
'qi'.repeat('3') // "qiqiqi"
Copy the code

4. Instance methods: 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 argument is the maximum length that string completion takes effect, and the second argument is the string used for completion.

If the length of the original string is equal to or greater than the maximum length, the string completion does not take effect and the original string is returned.

'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 maximum length, the completion string with more than 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

5. Example methods: trimStart(), trimEnd()

ES2019 adds the trimStart() and trimEnd() methods for string instances. They behave in the same way as trim(), with trimStart() eliminating whitespace at the head of the string and trimEnd() eliminating whitespace at the end. They all return a new string and do not modify the original string.

const s = ' abc ';

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

In the code above, trimStart() removes only the header whitespace and preserves the trailing whitespace. TrimEnd () behaves similarly.

In addition to the space bar, these methods also work with invisible whitespace characters such as the TAB key at the beginning (or end) of the string, and newlines.

The browser also deploys two additional methods, trimLeft(), which is an alias for trimStart(), and trimRight(), which is an alias for trimEnd().

6. Instance method: matchAll()

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