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 + ". "
thenengah
  • 42,557
  • 33
  • 113
  • 157
  • 1
    I think your question is exactly the same as this one: http://stackoverflow.com/questions/610406/javascript-printf-string-format – Alexandre Dec 14 '10 at 01:40
  • You need to declare variable var v = "sake" with a word reserved 'var', do you wrote this? – Cloudson Dec 14 '10 at 01:45
  • You should declare your variables with 'var', otherwise you pollute the global namespace. – Samo Dec 14 '10 at 17:55

1 Answers1

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

Alex Webb
  • 35
  • 4