Frekster
Frekster

Reputation: 1148

how do I dynamically add link text to a href in javascript?

I have this javascript code. When it renders it shows quotes around the text of the link rather than just the text. What is the syntax to properly concatinate the link text? My quotes are messed up but I cannot figure it out.

var link = "<a id=\"myLink\" href=\"\" target=\"_blank\">\"" + text + "\"</a>";

Upvotes: 2

Views: 1318

Answers (3)

Jashua White
Jashua White

Reputation: 81

Looks like you had extra quotes. You do not need to escape those around + text +. The following should work:

var link = "<a id=\"myLink\" href=\"\" target=\"_blank\">" + text + "</a>";

I prefer single quotes:

var link = '<a id="myLink" href="" target="_blank">' + text + '</a>';

When using the + operator to concatenate a variable and a string, you just have to keep track of opening and closing quotes. It can get tricky!

Similar example:

var str1 = "string";
var str2 = "This is how to concatenate a " + str1 + ".";
console.log(str2);

Upvotes: 5

KolaCaine
KolaCaine

Reputation: 2187

Check this code :

const text = 'My awesome link'
const link = "<a href='http://google.com' target='blank'>" + text + "</a>

console.log(link);

Upvotes: 0

Lolu Omosewo
Lolu Omosewo

Reputation: 263

Do this

var link = "<a id=\"myLink\" href=\"\" target=\"_blank\">" + text + "</a>";

Do not escape the quote before '+ text +'

Upvotes: 2

Related Questions