8

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 + ". "
3
  • 1
    I think your question is exactly the same as this one: stackoverflow.com/questions/610406/… Commented Dec 14, 2010 at 1:40
  • You need to declare variable var v = "sake" with a word reserved 'var', do you wrote this? Commented Dec 14, 2010 at 1:45
  • You should declare your variables with 'var', otherwise you pollute the global namespace. Commented Dec 14, 2010 at 17:55

1 Answer 1

0

This feature is supported in vanilla Javascript in the console.log function. The format would work as follows:

console.log('Hey %s', 'cat');

which results in

"Hey cat"

If you happen to be using Node.js, this functionality is supported out of box with the util.format(...) function, working pretty much the same way except that it just returns a string.

%s = string

%d = integer or float

%j = stringifyable object

Imo this approach might be slightly more idiomatic javascript than using an external library that simulates a ruby or C syntax, IF you are already using Node.js in some capacity.

https://nodejs.org/api/util.html#util_util_format_format

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.