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.

3
  • 2
    Well, you'd do it without the $, but alert(dog + " " + dog + " doo"); is the javascript way. Commented Feb 2, 2013 at 16:04
  • Just remove dollar signs from your example and it should work. Commented Feb 2, 2013 at 16:05
  • You could use some kind of sprintf implementation in JS: stackoverflow.com/questions/610406/…. Commented Feb 2, 2013 at 16:06

4 Answers 4

2

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

var dog = "fido"
dog + " " + dog + " doo"
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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'));

Comments

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);

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.