Capitalize the First Letter of a String in Nodejs


Program 1 :

Write a Node.js program that capitalizes and formats the command-line argument passed.

process_args.js
const nameArg = capitalize(process.argv[2] || "world");
console.log(`Hello ${nameArg}!`);
 
function capitalize(str) {
  return str
    .trim()
    .toLowerCase()
    .split(" ")
    .map((word) =>word.charAt(0).toUpperCase() + word.slice(1))
    .join(" ");
}
 

The program first imports the capitalize() function and defines a new variable nameArg that is equal to the capitalized and formatted version of the third element of the process.argv array (index 2). If the third element of process.argv is not provided, it defaults to the string "world".

The capitalize() function takes a string argument, trims any leading or trailing white spaces, converts the string to lowercase, splits it into an array of words, capitalizes the first letter of each word, and then joins the words back together into a single string.

For example, if you run the following command in the terminal:

node process_args.js "tutor joes"

The output would be:

Hello Tutor Joes!

If you run the following command instead:

node process_args.js

The output would be:

Hello World!

This program is an example of how to use command-line arguments in a Node.js program to customize its behavior, and how to define and use functions in Node.js.