Justin Meltzer
Justin Meltzer

Reputation: 13558

Interpolation in JavaScript

I have this jQuery code

$("#selector").html('<a href=url>text</a>');

where url and text are JavaScript variables. How would I evaluate them inside quotes?

Upvotes: 8

Views: 8165

Answers (3)

James Hibbard
James Hibbard

Reputation: 17775

For anyone landing here post 2015: use ES6 template literals. These are string literals, enclosed in backticks, which allow embedded expressions.

$('#selector').html(`<a href='${url}'>${text}</a>`);

Upvotes: 0

fncomp
fncomp

Reputation: 6198

While @kingjiv's answer is absolutely right, if you'll be doing a lot of templating with jQuery it might be worth checking out the tmpl* plugin to help keep things organized.

*note: This plugin never made it past beta, and is no longer being maintained, the link above is for archival purposes only.

Upvotes: 2

James Montagne
James Montagne

Reputation: 78690

You just concatenate the strings together with +:

$('#selector').html('<a href='+url+'>'+text+'</a>');

Upvotes: 11

Related Questions