3

Possible Duplicate:
JavaScript Variable inside string without concatenation - like PHP

In PHP, double quotes has the ability to read variable, e.g.

"$foo" 

But in JavaScript, you have to always use a + to read a variable so that the variable won't be inside the quote when it is read, e.g.

var foo='bar'; alert("The name's "+foo); 

So, is there any workaround or method to do this? Using + all the time is quite troublesome.

6
  • 2
    alert(["The name's ", foo].join('')); ;) Commented Jun 28, 2012 at 9:10
  • 1
    check this question stackoverflow.com/questions/1408289/… Commented Jun 28, 2012 at 9:12
  • @xdazz obviously more troublesome to do that haha Commented Jun 28, 2012 at 9:13
  • @FelixKling oopss.. I'll delete this question then. Commented Jun 28, 2012 at 9:14
  • @FelixKling And it looks like I can't do it :\ Commented Jun 28, 2012 at 9:15

2 Answers 2

1

Nope, that's not possible in JavaScript.

In JavaScript, variables are turned into string when put in single quotes or doubles quotes and can't be parsed. In JavaScript everything inside quotes is treated as string.

Even if you write custom parser, you will have no way to figure out if something in quotes is really a variable or an string because a variable named name can also appear in string somewhere which will create naming collisions.

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

Comments

1

No, there's no workaround, that's just how it is.

Javascript doesn't offer "string interpolation".

Personally I favour Ildar Shaimordanov's String.js module which adds a sprintf method to the string object.

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.