I'm attempting to set up a script to concatenate some variables inside a string if they exist, in order to place the appropriate metadata tags into a rendered HTML document.
My concatenation code is:
data = "<html>\n<head>\n" + "</head>\n<body>\n\n" + paras.join("\n\n") + "\n\n</body>\n</html>";
I'm trying to add if
statements like the following into it (between the first and second items):
if (typeof metadata_title !== "undefined") {
"<title>" + metadata_title + "</title>\n"
}
if (typeof metadata_author !== "undefined") {
"<meta name=\"author\" content=\"" + metadata_author + "\"></meta>\n"
}
if (typeof metadata_date !== "undefined") {
"<meta name=\"date\" content=\"" + metadata_date + "\"></meta>\n"
}
But I can't add any of these statements directly into the concatenation code
(it throws an error: Unexpected token (
).
How best would I go about adding statements such as these into my concatenation string?
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.
In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect. let myPet = 'seahorse'; console.
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.
In JavaScript, concat() is a string method that is used to concatenate strings together. The concat() method appends one or more string values to the calling string and then returns the concatenated result as a new string.
I'd use a ternary operator:
data = "<html>\n"
+ "<head>\n"
+ ( typeof metadata_title !== "undefined" ? "<title>" + metadata_title + "</title>\n" : "" )
+ ( typeof metadata_author !== "undefined" ? "<meta name=\"author\" content=\"" + metadata_author + "\"></meta>\n" : "" )
+ ( typeof metadata_date !== "undefined" ? "<meta name=\"date\" content=\"" + metadata_date + "\"></meta>\n" : "" )
+ "</head>\n"
+ "<body>\n"
+ "\n"
+ paras.join("\n\n")
+ "\n"
+ "\n"
+ "</body>\n"
+ "</html>"
;
data = "<html>\n<head>\n"
+ (
typeof metadata_title !== "undefined" ?
"<title>" + metadata_title + "</title>\n" :
""
)
+ (
typeof metadata_author !== "undefined" ?
"<meta name=\"author\" content=\"" + metadata_author + "\"></meta>\n" :
""
)
+ (
typeof metadata_date !== "undefined" ?
"<meta name=\"date\" content=\"" + metadata_date + "\"></meta>\n" :
""
)
+ "</head>\n<body>\n\n"
+ paras.join("\n\n")
+ "\n\n</body>\n</html>";
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