Anything similar in javascript to ruby's #{value} (string interpolation)
ES6 Update:
ES6 added template strings, which use backticks (`) instead of single or double quotes. In a template string, you can use the ${}
syntax to add expressions. Using your example, it would be:
string_needed = `prefix.....${topic}suffix....${name}testing`
Original answer:
Sorry :(
I like to take advantage of Array.join:
["prefix ....", topic, "suffix....", name, "testing"].join("")
or use String.concat
String.concat("a", 2, "c")
or you could write your own concatenate function:
var concat = function(/* args */) {
/*
* Something involving a loop through arguments
*/
}
or use a 3rd-party sprintf
function, such as http://www.diveintojavascript.com/projects/javascript-sprintf
Javascript string interpolation
72157640607666844
is too significant of a Number
for JavaScript to store completely:
console.log(72157640607666844);
// 72157640607666850
To avoid issues with precision, you can wrap the literal in quotes so it's a String
instead:
var fakeVar = '72157640607666844';
String formatting vs String Interpolation
String formatting is a rather general term of generating string content from data using some parameters. For example, creating date strings from date objects for a specific date format, number strings from numbers with a particular number of decimal digits or a number of leading spaces and zeroes etc. It can also involve templates, like in sprintf
function present in C or many other languages, or e.g. str.format
in Python. For example, in Ruby:
sprintf("%06.2f", 1.2) # float, length 6, 2 decimals, leading zeroes if needed
# => "001.20"
String interpolation is a much more restricted concept: evaluating expressions embedded inside string literals and replacing them with the result of such evaluation. For example, in Ruby:
"Two plus two is #{2+2}"
# => "Two plus two is 4"
Some languages can perform formatting inside interpolation. For example, in Python:
f"Six divided by five is {6/5:06.2f}"
# => "Six divided by five is 001.20"
The concepts are language-agnostic. However, it is not guaranteed that all programming languages will have a built-in capability for one or both of them. For example, C has no string interpolation, but it has string formatting, using the printf
family of functions; and until somewhat recently, JavaScript did not have either, and any formatting was done in a low-tech way, using concatenation and substringing.
How can I do string interpolation in JavaScript?
Since ES6, you can use template literals:
const age = 3console.log(`I'm ${age} years old!`)
How to handle the ruby like interpretation in JS
The problem you have is that you're trying to call the JS
variables inside the Ruby
code block.
Whilst there is whole other issue of the validity of using image_path
et al in JS
, the immediate point is that you have to make sure your JS vars are being read as such; not Ruby vars...
var current_package = this.id;
var current_style = $('.current-style').data('style');
$('.dp').attr('src', '<%= image_path("choose-package/' + current_style + '-' + current_package + '.png") %>');
The above should resolve your path issue. Whether it's valid in the context of your app is another question
In Ruby, can you perform string interpolation on data read from a file?
Instead of interpolating, you could use erb
. This blog gives simple example of ERB usage,
require 'erb'
name = "Rasmus"
template_string = "My name is <%= name %>"
template = ERB.new template_string
puts template.result # prints "My name is Rasmus"
Kernel#eval
could be used, too. But most of the time you want to use a simple template system like erb
.
String concatenation vs. interpolation in Ruby
Whenever TIMTOWTDI (there is more than one way to do it), you should look for the pros and cons. Using "string interpolation" (the second) instead of "string concatenation" (the first):
Pros:
- Is less typing
- Automatically calls
to_s
for you - More idiomatic within the Ruby community
- Faster to accomplish during runtime
Cons:
- Automatically calls
to_s
for you (maybe you thought you had a string, and theto_s
representation is not what you wanted, and hides the fact that it wasn't a string) - Requires you to use
"
to delimit your string instead of'
(perhaps you have a habit of using'
, or you previously typed a string using that and only later needed to use string interpolation)
Converting Ruby objects to Javascript objects for interpolation
No need to convert to a string and then JSON.parse:
"$('#foo').css(#{h.to_json});"
Or if you break it out...
var h = #{h.to_json};
"$('#foo').css(h);"
Which is rendered to the client as:
var h = {"background-color":"yellow","color":"green"};
$('#foo').css(h);
Ruby: eval with string interpolation
What's happening, is eval is evaluating the string as source code. When you use double quotes, the string is interpolated
eval '"123 #{456.to_s} 789"'
# => "123 456 789"
However when you use single quotes, there is no interpolation, hence the #
starts a comment, and you get
123 #{456.to_s} 789
# => 123
The string interpolation happens before the eval
call because it is the parameter to the method.
Also note the 456.to_s
is unnecessary, you can just do #{456}
.
Related Topics
JavaScript Date.Utc() Function Is Off by a Month
How to Use JavaScript in Ruby on Rails
Has Anyone Else Run into Problems Styling Twitter Typeahead's Searchbar
JavaScript in Wkwebview - Evaluatejavascript VS Adduserscript
Ruby with Watir: Handling JavaScript Popup Window
How to Export Tables to Excel from a Webpage
Correct Usage of Addeventlistener()/Attachevent()
Differencebetween 'Let' and 'Const' Ecmascript 2015 (Es6)
How to Scrape Data Using Ruby Which Is Generated by a JavaScript Function
Ruby Equivalent to JavaScript's Encodeuricomponent That Produces Identical Output
How to Get the Selected Radio Button Value Using Js
How to Implement Inheritance in Js Revealing Prototype Pattern
Why Does JavaScript's Eval Need Parentheses to Eval JSON Data