Template string flags for template strings that you don’t know about

What does the following code console output?

const value1 = "Okra";
const value2 = "Parsley";
const name = 'Brother Bear likes to eat${value1}And like to eat${value2}`;

console.log(name);
Copy the code

That’s easy. Brother Bear must like okra and cilantro

What if the code looks like this, what does the console print?

const value1 = "Okra";
const value2 = "Parsley";
const name = myTag'Brother Bear likes to eat${value1}And like to eat${value2}`;

function myTag(){}console.log(name);
Copy the code

Some of you might be able to guess that undefined will be printed, and it will be, but why does that happen?

A template string is no longer a template string, and its return value is completely controlled by the return value of the template function. MyTag returns undefined. So the template string prints undefined.

const value1 = "Okra";
const value2 = "Parsley";
const name = myTag'Brother Bear likes to eat${value1}And like to eat${value2}`;

Value1 is the value of ${value1} and value2 is the value of ${value2}
function myTag(strArr, value1, value2){
    console.log(strArr, value1, value2);
}

Copy the code

But what if there are more than one ${}? Can use… I can also expand operators, or I can use arguments. For example, IF I want to implement a function exactly like a template string, I can write it like this

const value1 = "Okra";
const value2 = "Parsley";
const name = myTag'Brother Bear likes to eat${value1}And like to eat${value2}. `;

Value1 is the value of ${value1} and value2 is the value of ${value2}
function myTag(){
    
    const argArr = [...arguments];  // Convert arguments to a true array
    const strArr = argArr[0].raw;   // Get an array of strings [" Bear likes to eat ", ", and likes to eat ", ""]
    const valArr = argArr.slice(1);  // Get an array of all ${} values [" okra ", "coriander "]
    let str = ' ';

    for(let i = 0; i < valArr.length; i ++){
        str += strArr[i] + valArr[i];
        if(i == valArr.length - 1){
            str += strArr[i + 1]; }}return str;
}

console.log(name);  // Brother Bear likes to eat okra and coriander...

Copy the code

For example, I can handle escaped characters. I want the String to be formatted and ignore escaped strings. I can use one of the built-in functions, String.raw

const name = 'a\nb';
console.log(name);  //a
                    //b

// If you use string. raw, the output will be unchanged. If you want to implement it, you can also use the re
const name = String.raw`a\nb`;
console.log(name);  //a\nb
Copy the code