New features of ES6: template strings

Source: Internet
Author: User
Tags access properties control characters microsoft edge

As the future of JavaScript, ES6 has arrived. As a finished standard, ES6 brings many new features that make it still competitive in today's web world. All aspects of ES6 are not necessarily suitable for you, this Assembly briefly introduces some of the new features that are handy and feasible.

I write JavaScript code that prefers to use single quotes to define strings rather than double quotes. Both are available for JavaScript, and the following two lines of code actually work the same way:

    1. var animal = "cow";
    2. var animal = ' cow ';

I prefer single quotes for a reason. First, single quotes are more convenient when combined with HTML strings and reference properties.

  1. With single quotes, there's no need to
  2. //Escape the quotes around the class value
  3. var but = ' <button class= ' big >Save</button> ';
  4. This is a syntax error:
  5. var but = "<button class="big">Save</button>";
  6. This works:
  7. var but = "<button class=\" big\ ">Save</button>";

You only need to escape when you use single quotes in HTML, and you rarely use single quotes in HTML. The scenario I can think of is nothing more than inline JavaScript or CSS, meaning that what you write at this time is unreliable or highly dependent on markup language. In the body, it is better to use the "rather than the single quote" instead of the typography. [^ Note: This means no escaping. ]

Side note: Of course, HTML is quite tolerant, you can delete quotes or use single quotes to wrap attributes, but I prefer to write better-readable markup language instead of relying too much on the parser. Today's HTML5 parser is so tolerant because the markup language that people have written in the past is too bad, and that's not an excuse to go on worse.
Using Document.writer within a frameset in the DHTML era creating documents on a new pop-up window I've had enough of this disgusting thing. I don't want to use escape characters anymore. I even sometimes use three quotes, which is still before the editor has color highlighting. It's a mess. Using variable substitution in strings

I prefer single quotes to one reason. I use PHP heavily when writing high-performance Web sites, and PHP distinguishes between single and double quotes. PHP single quotes do not allow variable substitution within strings, while double quotes allow.

This means that using single quotes in PHP 3 and PHP 4 is more efficient because the parser eliminates the hassle of retrieving the entire string for variable substitution. Take a look at the following example and you'll see:

    1. <?=
    2. $sound =
    3. echo ' the animal is $animal and it sound is $sound ' ;
    4. //= the animal is $animal and it is $sound /li>
    5. echo "The animal is $animal and it sound is $sound"
    6. //= the animal is cow and it sound is moo
    7. ?>

JavaScript does not support variable substitution within strings, so you have to use a concatenation string instead. This is obviously too troublesome and has to be frequently changed within quotations and citations.

    1. var animal = ' cow ';
    2. var sound = ' moo ';
    3. Alert(' The animal is ' + animal + ' and it is ' +
    4. Sound);
    5. = "The animal is cow and it is moo"
Trouble with multiple lines of string

It is really troublesome to handle increasingly long strings, especially when combined with lots of HTML. And it is likely that the Linting tool will end up with an error saying that there is more than one space behind the line. This is because JavaScript does not support multiple lines of string.

  1. It is not possible to write like this:
  2. var list = ' <ul>
  3. <li>buy milk</li>
  4. <li>be Kind to pandas</li>
  5. <li>forget about Dre</li>
  6. </ul> ';
  7. Can write like this, but, uh,
  8. var list = ' <ul>\
  9. <li>buy milk</li>\
  10. <li>be Kind to pandas</li>\
  11. <li>forget about Dre</li>\
  12. </ul> ';
  13. This is the most common notation, but, uh,
  14. var list = ' <ul> ' +
  15. ' <li>buy milk</li> ' +
  16. ' <li>be kind to pandas</li> ' +
  17. ' <li>forget about dre</li> ' +
  18. ' </ul> ';
Client-Side Template resolution

In order to solve the troublesome JavaScript string processing and splicing problems, still have to go to the old road, write a library. Among the many existing HTML template libraries, Mustache.js is probably the most influential. Most of these libraries follow a custom nonstandard grammar and use them to fully look at the mood. For example, it's like you write in markdown format and realize that "markdown" itself has a lot of different meanings. [Note: Markdown has many styles]

Using template strings

With the advent of ES6 and its standards, we are delighted to find that using JavaScript to process strings can use template strings. Support for template strings in mainstream browsers is now very timely: Chrome 44+, Firefox 38+, Microsoft Edge and Webkit all support. It's a pity that Safari hasn't been supported yet, but it won't be long.

The design genius of a template string is the use of a new string qualifier, which is an uncommon anti-quotation mark (') in HTML and ordinary text.

    1. var animal = ' cow ';
    2. var sound = ' moo ';
    3. Alert(' The Animal is ${animal} and it is ${sound} ');
    4. = "The animal is cow and it is moo"

${} accepts arbitrary JavaScript expressions and returns corresponding values, which can be used to perform mathematical operations or to access properties of objects and so on.

  1. var out = ' ten times ', Totally is ${* 2} ';
  2. = "Ten times totally is 20"
  3. var animal = {
  4. Name: ' cow ',
  5. Ilk: ' bovine ',
  6. Front: ' Moo ',
  7. Back: ' milk ',
  8. }
  9. Alert('
  10. The ${animal.name} is of the
  11. ${animal.ilk} ilk,
  12. One end is for the ${animal.front},
  13. The other for the ${animal.back}
  14. `);
  15. //=
  16. /*
  17. The cow is of the
  18. Bovine ilk,
  19. One end is for the Moo,
  20. The other for the milk
  21. */

The second example shows that multi-line strings are no longer a problem.

Tabbed templates

You can also add a label before the template string, which is used as the function name, and the string is the argument. The following example implements encoding of the returned string to generate the URL, avoiding always using unfriendly namedencodeuricomponent.

  1. function urlify (str) {
  2. return encodeuricomponent(str);
  3. }
  4. Urlify ' http://beedogs.com ';
  5. //= "http%3a%2f%2fbeedogs.com"
  6. Urlify ' woah$£$%£^$ ';
  7. //= "Woah%24%c2%a3%24%25%c2%a3%5e%24%22"
  8. Nesting also works:
  9. var str = ' foo ${urlify '&&'} bar ';
  10. = "Foo%26%26 bar"

This is used to be able to use, but relies on implicit array-to-string casts. The element passed to the function is not a string, but an array of strings and values. If used as above, it is automatically converted to a string for convenience, but the correct way is to access the array members directly.

Retrieving strings and values in a template string

Inside the label function, you can use not only the full string, but only part of the string.

  1. function tag (strings, values) {
  2. Console. Log(strings);
  3. Console. Log(values);
  4. Console. Log(strings[1]);
  5. }
  6. Tag ' You ${3+4} it ';
  7. /* =
  8. Array ["You", "it"]
  9. 7
  10. It
  11. */

You can also use an array of raw strings, which means that you can get all the characters in the string, and here says "All" refers to include control characters [^ Note: nonprinting characters]. For example, the control character is used when adding a newline. Only two spaces can be obtained in a string, and the \ n character is obtained in the original string.

  1. function tag (strings, values) {
  2. Console. Log(strings);
  3. Console. Log(values);
  4. Console. Log(strings[1]);
  5. Console. Log(string. Raw[1]);
  6. }
  7. Tag ' You ${3+4} \nit ';
  8. /* =
  9. Array ["You", "it"]
  10. 7
  11. It
  12. \nit
  13. */
Conclusion

The template string is a very nice little feature introduced by ES6 and can now be used. If you need to support older browsers, of course, you can also compile the ES6 conversion [Note: Transpile] back to ES5. You can also do feature detection for template strings, use libraries such as Featuretests.io, or use the following code:

  1. var templatestrings = false;
  2. Try {
  3. new Function( "' {+/-) '" );
  4. Templatestrings = true;
  5. } catch (err) {
  6. Templatestrings = false;
  7. }
  8. If (templatestrings) {
  9. //...
  10. } original link: http://www.gbtags.com/gb/share/9579.htm

New features of ES6: template strings

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.