In Delphi with object pascal, or in Visual Studio with C#, methods exist to concatenate different data types into a string. Wouldn’t it be nice to have a similar method in JavaScript? And what would the advantage be of such a method?
Advantage
- Use the same variable multiple times
- Gets the string value of any data type
- Apply special formatting (date/time/currency)
- Apply padding (left, right, special fill character)
JS Format string method
function FormatString(str, ...val) {
for (let index = 0; index < val.length; index++) {
str = str.replace("{"+ index + "}", val[index]);
}
return str;
}
Example to use the format string method
console.log(FormatString("/search?country={0}&province={1}&city={2}","nl_NL", "Overijssel", "Zwolle"));
The result looks like:
/search?country=nl_NL&province=Overijssel&city=Zwolle
You can use an online playground to test the code above.