ES6 Cool Stuffs — A new JS string with template literals

Cracking your head over string puzzle or relaxing with a template, which one you prefer? 😆

Strings in JavaScript

let str1 = 'hello'; //single quote
let str2 = "world"; //double quote
let str3 = String('test me');
str1.replace('ell', 'el'); //helostr1 += " " + str2; //helo world
let name = "Maya",
    greetings = str1 + ", my name is " + name; let greetings2 = [str1, ", my name is ", name].join('');
let longStr = "I'm a super long long long long long long\" + 
" long long long long long long\" +
" long long long long long long\" +
" long long long long long long\" +
" text. Check me out!";
let isWorld = true;let printStr1 = "Hello " + isWorld ? "World" : "me";
console.log(printStr1); //World//Need to use () to wrap expression
let printStr2 = "Hello " + (isWorld ? "World" : "me");
console.log(printStr2); //Hello World
let rhyme = "Are you sleeping? Are you sleeping?\nBrother John, Brother John!\nMorning bells are ringing!\nMorning bells are ringing!\nDing, ding, dong.\nDing, ding, dong.";
let person = {
    name: "Maya",
    hobbies: ["reading", "drawing", "traveling"],
    job: "Developer"
};function personTemplate(person){
    return "<article class='person'>" +
                "<h3>" + person.name + "</h3>" +   
                "<p> Hobbies: " + person.hobbies +  "</p>" +
                "<p> Current job: " + person.job + "</p>" +                         
           "</article>";
}document.write(personTemplate(person));
let paragraph = "Paragraph: \n" +
"\t1. Point 1:\n" +
"\t\t1.1 Sub-point 1:\n" +
"\t\t1.2 Sub-point 2:\n" +
"\t2. Point 2:\n" +
"\t\t2.1 Sub-point 1:\n" +
"\t\t2.2 Sub-point 2:\n" +
"\t3. Point 3:\n" +
"\t\t3.1 Sub-point 1:\n" +
"\t\t3.2 Sub-point 2:\n" +
"Conclusion: I'm exhausted! Did I miss anything?";console.log(paragraph);
let introduction = 'My name is "Maya Shavin", I' + "'m using single quote (') and double quote " + '(") here';

What is template literals?

How does it work?

Basic Syntax

let myStr = `my new string`;let introduction = `My name is "Maya Shavin", I'm using single quote (') and double quote (") here`;

Expressions/Variables interpolation (of course)

let welcome = "Hello " + (isWorld ? "World" : "me");
let welcome = `Hello ${isWorld ? "World" : "me"}!`;
let meBe = {
    firstName: "Maya",
    lastName: "Shavin",
    get welcome(){
        return `Hi there, I'm ${this.firstName} ${this.lastName}`;
    }
}console.log(meBe.welcome); //Hi there, I'm Maya Shavin

Multi-lines strings and indented strings

let paragraph = 
`Paragraph:
    1. Point 1:
       1.1 Sub-point 1:
       1.2 Sub-point 2:
    2. Point 2:
       2.1 Sub-point 1:
       2.2 Sub-point 2:
    3. Point 3:
       3.1 Sub-point 1:
       3.2 Sub-point 2:
Conclusion: I'm exhausted! Did I miss anything?`;console.log(paragraph);

HTML templates

function personTemplate(person){
    return "<article class='person'>" +
                "<h3>" + person.name + "</h3>" +   
                "<p> Hobbies: " + person.hobbies +  "</p>" +
                "<p> Current job: " + person.job + "</p>" +                         
           "</article>";
}
function personTemplate({name, hobbies, job}){
   return `<article class="person">
   <h3>${name}</h3>
   <div>
       <div>Hobbies:</div>
       <ul>
           ${hobbies.map(hobby => `<li>${hobby}</li>`).join(" ")}
       </ul>
   </div>
   <p>Current job: ${job}</p>
</article>`;
}

Limitations

No built-in syntax for looping

let days = ["Mon", "Tue", "Wed", "Thurs", "Fri", "Sat", Sun"];
let table = `<ul>
   ${days.map(day => `<li>${day}</li>`).join(" ")}
</ul>`;
let table = "<ul>";
for (let i = 0; i < days.length; i++){
    table += `<li>${days[i]}</li>`;
}table += "</ul>";

No support for different languages and locales format

Tagged template literals

`My name is ${name}, and I'm ${age} years old`
["My name is", ", and I'm ", " years old"], <value of name>, <value of age>

How do we pass it to function call?

func(`My name is ${name}, and I'm ${age} years old`); //Wrongfunc`My name is ${name}, and I'm ${age} years old`; //Correct
func([“My name is”, “, and I’m “, “ years old”], <value of name>, <value of age>);
let name = "Maya", age = "30";parseStr`My name is ${name}, and I'm ${age} years old`;function parseStr(templates, name, age){
     console.log('Template: ', templates);
     console.log('Param 1: ', name);
     console.log('Param 2: ', age);
}

Sound advanced but not very useful, doesn’t it? So what will it be good for?

function getRaw(templates){
    console.log(templates.raw[0]);
}getRaw`One line\nTwo line\n`; //One line\nTwo line\n
console.log(`One line\nTwo line\n`);
//One line
//Two linegetRaw`Heading\n\tSub-Heading`; //Heading\n\tSub-Heading
console.log(`Heading\n\tSub-Heading`);
//Heading
//    Sub-Heading

Performance


Conclusion


Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Maya Shavin

Written by

Senior Front-End Developer @Cloudinary www.mayashavin.com

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co