Inserting values into a string JS example. Interpolation open

Inserting values into a string JS example. Interpolation

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: ES6

String templates allow you to insert different values into a string. To do this, the strings are enclosed in slash quotes, and the value to be inserted is preceded by the $ symbol and enclosed in curly braces:

    const name = "Alexander";
    const hello = `Hello ${name}`;
    console.log(hello);// Hello Alexander

In a similar way, several values can be inserted into a string at the same time:

    const name = "Alexander";
    const age = 33;
    const hello = `Name: ${name}, age: ${age}`;
    console.log(hello);// Name Alexander, age 33

Also, instead of the values of constants and variables, you can add the values of complex objects:

    const alex = {
        name: "Alexander",
        age: 33
    }

    const info = `${alex.name} is ${alex.age} years old`;
    console.log(info);       // Alexander is 33 years old

You can also insert more complex calculated expressions:

    function sum(x, y) {
        return x + y;
    }

    let a = 5;
    let b = 4;

    const result = `${a} + ${b} = ${sum(a, b)}`;
    console.log(result);    // 5 + 4 = 9

HTML in string templates


<head>
    <title>Test</title>
</head>

<body>

    <script>
        const alex = { name: "Alexander", age: 33 };

        const markup = `<div>
    <p><b>Name</b>: ${alex.name}</p>
    <p><b>Age</b>: ${alex.age}</p>
</div>`;

        document.body.innerHTML = markup;

    </script>
</body>

Another example, let’s create an HTML list from array elements:

<head>
    <title>Test2</title>
</head>

<body>
    <script>

        const people = [{ name: "Alexander", age: 33 }, { name: "Timote", age: 26 }, { name: "Rob", age: 35 }];

        const markup = `<ul>
    ${people.map(person => `<li>${person.name}</li>`)}
</ul>`;

        document.body.innerHTML = markup;
    </script>
</body>

Passing a String Template to a Function

JavaScript allows you to pass a string template to a function, and not just as a string, but all of its dynamically calculated fragments as separate parameters.

Let’s look at an example:


<head>
    <title>Test 3</title>
</head>

<body>
    <script>

        const person = "Alex";

        function check(parts, name) {
            return parts[0] + name + parts[1];
        }

        let checkedTemplate = check`Person: ${person}.`;

        console.log(checkedTemplate);

        document.body.innerHTML = checkedTemplate;
    </script>
</body>

The parts parameter is an array of template parts separated by dynamic fragments to be inserted.
Name is a dynamically evaluated template fragment.
From the console output, we can see that the elements of the parts array are the substrings “Person: ” and “.“.

And the string “Alexander” is passed as the value of the name parameter.
It is worth noting that even if there were no more characters after the dynamically calculated fragment (for example, `Person: ${person}`), then the parts array would still have two elements, only the second element would then be empty line.

We can do some processing if needed:

    const alex = "Alexander";
    const admin = "Admin";

    function check(parts, name) {
        if (name === "Admin") return "Wrong user";

        else return parts[0] + name + parts[1];
    }

    let checkedTemplate1 = check`user: ${alex}`;
    let checkedTemplate2 = check`user: ${admin}`;

    console.log(checkedTemplate1);
    console.log(checkedTemplate2);

Templates with a large number of computed fragments can be handled in a similar way:

    const alex = { name: "Alexander", age: 33 };
    const bob = { name: "Bob", age: 11 };

    function check(parts, name, age) {
        if (age > 18) return `${parts[0]}${name}. Closed`;
        else return ` ${name} closed. User ${age} is not enough years`;
    }

    let checkedTemplate1 = check`User: ${alex.name} ${alex.age}`;
    let checkedTemplate2 = check`User: ${bob.name} ${bob.age}`;

    console.log(checkedTemplate1);
    console.log(checkedTemplate2);

In this case, the template contains two dynamic fragments. Accordingly, the part array will have three elements.

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation