0

In php you can use variables inside of double-quotes. eg:

$dog = "scooby";
echo "$dog $dog doo";

Is it possible to do something similar in javascript without breaking the string up into pieces:

var dog = "scooby";
alert($dog + " " + $dog + " doo");

Thanks (in advance) for your help.

user1031947
  • 6,294
  • 16
  • 55
  • 88

4 Answers4

2

No, you can’t. Javascript does not have string interpolation, so you must concatenate:

var dog = "fido"
dog + " " + dog + " doo"
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
1

No, since there is no escape character for variables in JavaScript.

Tomer Arazy
  • 1,833
  • 10
  • 15
1

Natively, not possible. However if you don't mind using a library, you can use this Javascript implementation of sprintf.

Instead of:

var dog = "scooby";
alert($dog + " " + $dog + " doo");

You would use:

alert(sprintf('%s %s doo', 'dog', 'dog'));
Josh
  • 11
  • 1
  • 2
0

All you need to do is use string replace

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace

If you want it to be done depending upon the token, you'd need a little more work:

function replacer(match, p1,  string){
  // p1 is the first group (\w+)
  var stuff = {
     dog: "woof", 
     cat: "meow"
  };
  return stuff[p1] || "";
};
newString = "A dog says $dog. A cat says $cat.".replace(/\$(\w+)/g, replacer);

results in

"A dog says woof. A cat says meow."

Edit: Actually, if you want to do a kind of string interpolation on global variables, it's also pretty easy, though I wouldn't recommend this. Please don't unless you have a really good reason. And if you say you have a good reason, I probably wouldn't believe you. My first example, where I give a particular dictionary/object to search, is much better. Please don't go about polluting the global namespace just because this works!

var dog ="woof";
var cat = "meow";
function replacer(match, p1,  string){
  return window[p1] || "";
};
newString = "A dog says $dog. A cat says $cat.".replace(/\$(\w+)/g, replacer);
JayC
  • 7,053
  • 2
  • 25
  • 41