JavaScript String Format: Methods with EXAMPLES

What is JavaScript String Format?

JavaScript String format refers to the approaches that can be used for manipulating and formatting strings in a defined form. It is a crucial feature of any programming language that permits you to have control over the text that appears in your application.

In your JavaScript code, string formatting can transform complex data in a simple way. It also improves the output readability and makes the code more maintainable. Additionally, properly formatted JavaScript strings can also play a role in enhancing the user experience of the application.

How to Format Strings in JavaScript?

In order to format a string in JavaScript, follow the provided steps:

Step 1) First, it is required to determine the data that you want to include in the string.

Step 2) Then, select a method to format string in JS.

Step 3) Write the code for its implementation accordingly.

Step 4) Test the code to make sure that it generates the expected output.

Step 5) Update or modify the code to meet the additional formatting needs or requirements.

Step 6) Refactor the code for maintainability and readability.

Different String Formatting Methods in JavaScript

There exist multiple ways to format strings in JavaScript, including concatenation operators, template literals, regular expressions, and more.

In the next section, you will explore the following approaches:

  • {} Brackets with backticks
  • “+” Operator
  • Custom function String Formatting
  • Concatenation operator
  • Template literals
  • Regular expression
  • Custom function
  • Ternary operator

Method 1: Using {} Brackets with Backticks to Format String in JavaScript

In this method, you can use template literals by adding backticks (`) for enclosing a string. Then, insert variables of the string arguments in brackets {} preceded with a dollar sign “$”. These templates enable you to embed expressions within a string literal.

This operation helps to concatenate variables called placeholders and other defined values. Resultantly, the final formatted string is obtained by interpolating the values of placeholders.

For example, we have created two variables, “name” and “id,” and then enclosed them in backticks for generating the formatted output. Note that the “${}” syntax is used for embedding the expressions with the string.

Code:

const name = "Jenny";
const id = 1;
console.log (`Welcome ${name}, your ID is ${id}`);

It can be observed that the values of the placeholder’s “name” and “id” have been displayed, which means string interpolation has been performed successfully.

Output:

Welcome Jenny, your ID is 1

Method 2: Using + Operator to Format String in JavaScript

The second approach is to use the Concatenation operator +” for basic formatting strings in JavaScript. This way involves concatenating the individual variables and strings together to generate the desired output.

For instance, we have now used the “+” operator to concatenate the same variable values, and the “console.log()” method will return a formatted string on the console.

Code:

const name = "Jenny";
const id = 1;
console.log("Welcome " + name + ", your ID is " + id);

Output:

Welcome Jenny, your ID is 1

Method 3: Custom function String Formatting in JavaScript

In your JavaScript program, you can also use the custom function string formatting approach. In this technique, the function accepts the desired variables and returns the formatted string. This format function also offers a lot of flexibility. You can also use it to fulfill custom or complex formatting requirements.

Here, we have created a custom format function named “welcomeMsg()” that accepts two variables “name” and “id” as arguments and outputs formatted strings by utilizing the template string literals.

After that, we defined the desired variables and passed them in the format custom formation function call.

Code:

function welcomeMsg(name, id) {
  return `Welcome ${name}, your ID is ${id}`;
}
const name = "Jenny";
const id = 1;
const msg = welcomeMsg(name, id);
console.log(msg);

Output:

Welcome Jenny, your ID is 1

Method 4: Using Concatenation for Format String in JavaScript

Concatenation is a simple method utilized for formatting strings in JavaScript. This approach involves combining string variables or multiple strings together using the concatenation operator “+”. You can also use this technique for simple string concatenation tasks.

In the provided example, the variables “firstName” and “lastName” will be concatenated with the help of the “+” operator to form the “fullName” string as follows.

Code:

var firstName = "Alex";
var lastName = "Edward";
var fullName = firstName + " " + lastName;
console.log(fullName);

Output:

Alex Edward

Method 5: Using Template Literals for Format String in JavaScript

Template strings which are also known as Template literals offer a more expressive and advanced way to format strings in JavaScript. They permit the direct embedding of expressions and variables within the string using the placeholder “${expression}”.

Moreover, template literal also provides support to the multi-line strings.

Code:

var name = "Alex";
var age = 30;
var msg = `Hi, ${name}! You are ${age} years old.`;
console.log(msg);

In the above example, we have directly interpolated the variable “name” and “age” within the string by utilizing the placeholders “${}” within the backticks (`) of the template literals.

Output:

Hi, Alex! You are 30 years old.

Method 6: Using Regular Expressions to Format String in JavaScript

In JavaScript code, Regular expressions are the robust tool used for string manipulation and pattern matching. Moreover, they are also utilized for finding the given pattern and replacing them with defined values. This operation can be done with the help of the “replace ()” method.

Check out the below program, the replace () method is used with two regular expressions that will replace the placeholders “[name]” and “[id]” with the respective value.

Code:

let name = "Jenny";
let id = 1;
let message = "Welcome [name], your ID is [id]".replace(/\[name\]/g, name).replace(/\[id\]/g, id);
console.log(message);

This results in a new string object that will be stored in the “message” variable logged on the console as output.

Output:

Welcome Jenny. Your ID is 1

Method 7: Using a Custom function for Format String in JavaScript

You can also create a more reusable and customized string format in JavaScript. To do so, define a new custom function that accepts a string and other parameters. You can call it to replace placeholders or apply custom formatting rules. This technique also supports customized formatting in complex formatting scenarios.

Here, we have created a new custom function format named “formatString” that accepts a “string” and “params” (array of parameters) as arguments.

Within the function body, we have invoked the “replace()” method with a regular expression for replacing placeholders “{0}, {1}” with their respective values from the parameters array.

Code:

function formatString(string, params) {
  return string.replace(/{(\d+)}/g, (match, index) => {
    return typeof params[index] !== 'undefined' ? params[index] : match;
  });
}
var name = "Alex";
var age = 30;
var formattedMsg = formatString("Hi, {0}! You are {1} years old.", [name, age]);
console.log(formattedMsg); 

Output:

Hi, Alex! You are 30 years old.

Method 8: Using Ternary Operator to Format String in JavaScript

JavaScript Ternary operator is a shorthand way for writing conditional expressions on strings. However, it can be also used for string formatting by conditionally selecting one of two values according to the specified boolean expression and returning the string.

Syntax:

condition ? expressionIfTrue : expressionIfFalse

Have a look at this example code of using a ternary operator to format into a string object.

Code:

let name = "Jenny";
let isAdmin = true;
let msg = `Welcome ${name}${isAdmin ? ", you are an admin" : ""}`;
console.log(msg);

Output:

Welcome Jenny, you are an admin

Here, we have defined two variables “name” and “isAdmin” with the values “Jenny” and “true”, respectively.

After that, we utilized the ternary operator to conditionally add the string “, you are an admin” to the message string if the value of the optional parameter “isAdmin” is true, as stated above.

Comparison of JavaScript String Format Methods

Here, we have enlisted the advantages and disadvantages of the above-discussed JavaScript string format methods:

Method Advantages Disadvantages
Brackets {} with backticks (`) • Easy to use.
• Concise and readable code.
It may not be appropriate for more complex formatting requirements.
“+” operator Easy to understand. Can be inefficient for more complex formatting requirements.
Custom function for String formatting Offers a lot of flexibility. Needs more coding effort.
Concatenation Operator Simple and widely supported. Cumbersome for complex string formatting.
Template Literals • Supports multi-line strings.
• Readable and Intuitive syntax.
Limited control over formatting options.
Regular Expressions Provide a lot of flexibility. Different implementation and maintenance as compared to other methods.
Custom function Provides a lot of flexibility. Needs additional coding for creating and maintaining a custom function.
Ternary operator Concise way for handling null or undefined values. It might not be suitable for more complex formatting requirements.

Note that the selection of the method highly depends on the specific use case and the relevant requirements of your JavaScript code.

Conclusion

In JavaScript, you can use template literals, the ternary operator, “+” operator, regular expressions, and the custom function to format strings. These string format methods permit developers to manipulate and present textual data in an efficient manner.

Thus, select the right method based on readability, performance, and browser compatibility. It empowers developers to improve user experiences and achieve desired formatting standards.