In ruby you can insert variables into a string like this:
x = "sake"
puts "I like #{x}"
$"I like sake"
For example:
def what_i_like(word)
"I like #{word}"
end
Is there a similar way to do this in javascript?
What I'm doing now is this:
x = "sake"
"I like" + x + ". "
You can add in-line javascript in your view templates and interpolate ruby variables. HAML supports ruby interpolation under the :javascript tag with the #{} syntax. Using #{} by itself can result in errors.
You write the string as normal but for the variable you want to include in the string, you write the variable like this: ${variableName} . For the example above, the output will be the same as the example before it that uses concatenation.
To declare variables in JavaScript, you need to use the var, let, or const keyword. Whether it is a string or a number, use the var, let, or const keyword for its declaration. But for declaring a string variable we had to put the string inside double quotes or single quotes.
Check out this post: JavaScript equivalent to printf/string.format
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