How to Format String in Javascript?

Here is how you can format string in Javascript! Use it when you need to work with string in Javascript.

Format with backtick

let firstName = 'Ahmad'
let lastName = 'Rosid'
const fullName = `${firstName} ${lastName}`

Format with plus operator

let age = 24
let ageString = "My age is " + age + " year's old"

Replace string

let fullName = "Ahmad Rosid"
let username = fullName.replace(" ", "").toLowerCase()

Replace all

let fullName = "Maulana Ibrahim Rosid"
let username = fullName.replaceAll(" ", "_")

Replace string with regex

const coding = "I watch video from TV";
const replacedString = coding.replace(/TV/, "YouTube");

console.log(replacedString);

NodeJS util package

const util = require('util');
let firstName = "Ahmad"
let lastName = "Rosid"
const fullName = util.format('%s %s', firstName, lastName);

Array Join

let data = ["Ahmad", "Rosid"]
let fullName = data.join(" ")