Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I know in PHP we can do something like this :

$hello = "foo";
$my_string = "I pity the $hello";

output : "I pity the foo"

I was wondering if this same thing is possible in JavaScript as well. Using variables inside strings without using concatenation -- it looks more concise and elegant to write.

share|improve this question

5 Answers

up vote 23 down vote accepted

Nope that is not possible in javascript. You will have to resort to:

var hello = "foo";
var my_string = "I pity the " + hello;
share|improve this answer
Okay, Thanks.... – DMin Jul 21 '10 at 21:32
1  
@DMin: You are welcome. – Sarfraz Jul 21 '10 at 21:32

Take a look at below, it does same! http://code.google.com/p/jsstring/

PS : Too late answer, but if someone come to this by searching they may find it useful.

share|improve this answer

well you could do this, but it's not esp general

'I pity the $fool'.replace('$fool', 'fool')

You could easily write a function that does this intelligently if you really needed to

share|improve this answer

If you're trying to do interpolation for microtemplating, I like Mustache.js for that purpose.

share|improve this answer

No, although you could try sprintf for JavaScript to get halfway there:

var hello = "foo";
var my_string = sprintf("I pity the %s", hello);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.