JavaScript JS Tutorial JS Objects JS Functions JS Classes JS Async JS HTML DOM JS Browser BOM JS Web APIs JS AJAX JS JSON JS vs jQuery JS Graphics



JS String Templates

JavaScript (JS) is a popular programming language used for creating dynamic web pages. One of the most important features of JS is its ability to manipulate strings. JS String Templates are a powerful tool that allows developers to create dynamic strings with ease.

JS String Templates are a way to embed expressions inside string literals, using backticks (`) instead of single or double quotes. This allows for more flexibility and readability when creating strings that contain variables or expressions.

Here is an example of a basic JS String Template:


const name = 'John';
const age = 30;
const message = `My name is ${name} and I am ${age} years old.`;
console.log(message);

In this example, we have defined two variables, 'name' and 'age', and used them inside a string template to create a dynamic message. The expression inside the curly braces (${...}) is evaluated and the result is inserted into the string.

JS String Templates can also be used for more complex expressions, such as conditional statements and loops. Here is an example:


const items = ['apple', 'banana', 'orange'];
const list = `
  
    ${items.map(item => `
  • ${item}
  • `).join('')}
`; console.log(list);

In this example, we have defined an array of items and used a string template to create an unordered list of those items. The 'map' method is used to create a new array of list items, and the 'join' method is used to concatenate the items into a single string.

JS String Templates can also be used for more advanced features, such as tagged templates. Tagged templates allow developers to define a function that can modify the output of a string template. Here is an example:


function highlight(strings, ...values) {
  return strings.reduce((result, string, i) => {
    return result + string + (values[i] ? `${values[i]}` : '');
  }, '');
}

const name = 'John';
const age = 30;
const message = highlight`My name is ${name} and I am ${age} years old.`;
console.log(message);

In this example, we have defined a 'highlight' function that takes a string template and modifies it by wrapping any values in a 'strong' tag. The function is then used to create a dynamic message with the 'name' and 'age' variables.

JS String Templates are a powerful tool that can greatly simplify the process of creating dynamic strings in JavaScript. They allow for more flexibility and readability, and can be used for a wide range of applications.

References

Activity