Dan
Dan

Reputation: 946

Javascript syntax for concatenating in URL

I can show orderB.id as table data. I want to use this value in the href, but I am struggling with syntax.

        var output = results.reduce(function (orderA, orderB){
            var row = "<tr>";
            row += "<td>" + orderB.name + "</td>";
            row += "<td>" + orderB.type + "</td>";
            row += "<td>" + orderB.id + "</td>";
            row += "<td><a href='/update/' + orderB.id + >Update</a></td>";
            return orderA + row;
        },"")

I have tried:

            row += "<td><a href='/update/' + orderB.id + >Update</a></td>";
            row += "<td><a href='/update/' + 'orderB.id' + >Update</a></td>";
            row += "<td><a href='/update/orderB.id' + >Update</a></td>";

These output:

  1. /update/
  2. /update/
  3. /update/orderB.id

I want for example: /update/3

Upvotes: 0

Views: 44

Answers (2)

Taki
Taki

Reputation: 17654

use template literals :

row += `<td><a href="/update/${orderB.id}">Update</a></td>`;

or simply concat your variables with the htmml string like :

row += '<td><a href="/update/' + orderB.id + '">Update</a></td>';

Upvotes: 2

kshetline
kshetline

Reputation: 13700

As has been suggested, template literals are a good way to go, but you have to be careful about just sticking strings together to create HTML -- if there are characters like <, >, or & there can be problems. I'd use Lodash and modify the answer given by another poster like this:

row += `<td><a href="/update/${_.escape(orderB.id)}">Update</a></td>`;

Upvotes: 0

Related Questions