Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anything similar in javascript to ruby's #{value} (string interpolation) [duplicate]

i am tired of writing this:

string_needed="prefix....." + topic + "suffix...." + name + "testing";

i would think someone might have done something about this by now ;)

like image 382
meow Avatar asked Jan 20 '11 03:01

meow


People also ask

Is JavaScript similar to Ruby?

Ruby vs JavaScript Summary In short, Ruby is an object oriented language typically used for server side development. JavaScript is also object oriented and typically used for client side applications. JavaScript is far more widely used than Ruby, although Ruby is still a strong language.

Is Ruby or JavaScript better?

All in all, the fact that JavaScript can be used to build a full-stack application and that it is a lot faster than Ruby has turned it into the more popular language. Uber, Paypal, LinkedIn are some examples of companies who have switched from Ruby to JavaScript in recent years.

Is Ruby a JavaScript framework?

On one side, where Ruby on Rails is a server-side web application framework written in Ruby while JavaScript is a programming language that is one of the core technologies of the World Wide Web (WWW). GitHub Oververse 2021 Report statistics state that JavaScript is the most used language worldwide.

What is the difference between Ruby on Rails and JavaScript?

Ruby on Rails is used for backend development, while Javascript is used for client side frontend development. However, JavaScript can also be used for back end development with different Javascript based languages and development frameworks.


2 Answers

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

like image 74
erjiang Avatar answered Sep 23 '22 23:09

erjiang


You could consider using coffeescript to write the code (which has interpolation like Ruby ie #{foo}).

It 'compiles' down to javascript - so you will end up with javascript like what you've written, but without the need to write/maintain the +++ code you're tired of

I realize that asking you to consider another language is on the edge of being a valid answer or not but considering the way coffeescript works, and that one of your tags is Ruby, I'm hoping it'll pass.

like image 23
PandaWood Avatar answered Sep 25 '22 23:09

PandaWood