Assign a combined string to href tag in HTML

Viewed 4174

I have some rows in a table I want to set every row as a link by using href tag in HTML. The structure of my links is something like this:

http://www.itsecdb.com/oval/oval-definition-details.php?ovaldefinitionid=oval%3Aorg.mitre.oval%3Adef%3A9278&s=1

I want to set "org.mitre.oval" and "9278" parts as a variable so I can change them based on the value of each row. something like this:

 X and Y are variables
 <a href = "http://www.itsecdb.com/oval/oval-definition-details.php?ovaldefinitionid=oval%3A" + X +"%3Adef%3A" + Y + "&s=1" >row</a>

but href tag does not support this kind of concatenation.
Any idea how can I seperate those parts and put my values in them?
Thanks in advance.

3 Answers

The following demo is a solution for multiple links.

Demo

var xArray = ['2813224', '8472040'];
var yArray = ['zer00ne', 'afsane'];
var lnx = document.links;

for (let i = 0; i < lnx.length; i++) {
  var X = xArray[i];
  var Y = yArray[i];
  var base = `https://stackoverflow.com/users/${X}/${Y}?tab=profile`;
  lnx[i].href = base;
  lnx[i].textContent = Y;
}
<a href=''></a><br>
<a href=''></a>

try to add href in javascript :

var X=1;
var Y=2;
var a = document.getElementById('mylink'); 
a.href = "http://www.itsecdb.com/oval/oval-definition-details.php?ovaldefinitionid=oval%3A" + X +"%3Adef%3A" + Y + "&s=1";
 <a href = "" id="mylink" target="_blank">row</a>

You can do so using template literal `` and substitute using ${varaiable}template literal

 <a href=`http://www.itsecdb.com/oval/oval-definition-details.php?ovaldefinitionid=oval%3A${X}%3Adef%3A${Y}&s=1` id="mylink">row</a>

Related