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 template literals
Template literals are string literals that allow embedded expressions. You can use placeholders (${expression}) to specify where you want the expression to be inserted in the string.
let firstName = 'Ahmad'
let lastName = 'Rosid'
const fullName = `${firstName} ${lastName}`
Format with concatenation
You can use the + operator to concatenate strings and variables.
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(" ")