Does JavaScript support substitution/interpolation?
I'm working on a JS project, and as it's getting bigger, keeping strings in good shape is getting a lot harder. I'm wondering what's the easiest and most conventional way to construct or build strings in JavaScript.
My experience so far:
String concatenation starts looking ugly and becomes harder to maintain as the project becomes more complex.
The most important this at this point is succinctness and readability, think a bunch of moving parts, not just 2-3 variables.
It's also important that it's supported by major browsers as of today (i.e at least ES5 supported).
I'm aware of the JS concatenation shorthand:
var x = 'Hello'; var y = 'world'; console.log(x + ', ' + y);
And of the String.concat function.
I'm looking for something a bit neater.
Ruby and Swift do it in an interesting way.
Ruby
var x = 'Hello' var y = 'world' print "#{x}, #{y}"
Swift
var x = "Hello" var y = "world" println("\(x), \(y)")
I was thinking that there might be something like that in JavaScript maybe something similar to sprintf.js.
Can this be done without any third party library? If not, what can I use?
The + Operator The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b . If the left hand side of the + operator is a string, JavaScript will coerce the right hand side to a string.
When concatenating three dynamic string values or less, use traditional string concatenation. When concatenating more than three dynamic string values, use StringBuilder . When building a big string from several string literals, use either the @ string literal or the inline + operator.
You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
With ES6, you can use
Template strings:
var username = 'craig'; console.log(`hello ${username}`);
ES5 and below:
use the +
operator
var username = 'craig'; var joined = 'hello ' + username;
String's concat(..)
var username = 'craig'; var joined = 'hello '.concat(username);
Alternatively, use Array methods:
join(..)
:
var username = 'craig'; var joined = ['hello', username].join(' ');
Or even fancier, reduce(..)
combined with any of the above:
var a = ['hello', 'world', 'and', 'the', 'milky', 'way']; var b = a.reduce(function(pre, next) { return pre + ' ' + next; }); console.log(b); // hello world and the milky way
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With