Skip to content

JavaScript string format placeholder

JavaScript string placeholders are used to represent dynamic values that will be inserted into a string. There are several ways to define placeholders in JavaScript, including using curly braces and an index number, using curly braces and a property name, or using backticks and ${}.

JavaScript string format placeholder example

Simple example code of several ways to define placeholders in JavaScript strings.

1. Using curly braces and an index number:

let name = "John";
let message = "Hello, {0}!";
message = message.replace("{0}", name);
console.log(message); // Hello, John!

2. Using curly braces and a property name

let person = { name: "John", age: 30 };
let message = "My name is {name} and I'm {age} years old.";
message = message.replace(/{([^{}]*)}/g, function(match, property) {
  return person[property];
});
console.log(message); // My name is John and I'm 30 years old.

3. Using backticks and ${}:

let name = "John";
let message = `Hello, ${name}!`;
console.log(message); // Hello, John!

Here’s another example of using placeholders with an object and a regular expression to create a dynamic message:

<!DOCTYPE html>
<html>
<head>
  <script>
    let person = { 
        name: "John", 
        age: 30, 
        occupation: "Software Engineer" 
    };

    let message = "Hi, my name is {name}, I'm {age} years old, and I work as a {occupation}.";

    message = message.replace(/{([^{}]*)}/g, function(match, property) {
    return person[property];
    });

    console.log(message);

  </script>
</head>
<body>
  
</body>
</html>

Output:

JavaScript string format placeholder

The regular expression /{([^{}]*)}/g matches any substring enclosed in curly braces that does not contain curly braces inside it.

By using placeholders, you can create dynamic, customizable strings that can be used in a variety of applications, such as generating personalized messages or formatting dates and numbers.

Do comment if you have any doubts or suggestions on this JS string format topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading