Search code examples
javascriptstringconcatenation

How to concatenate strings with quotes to another string with multiple quotes on JS


I'm trying to write JS code and I have to concatenate multiple strings with variables in them to form a giant string.

var another_class = 'datatables-more';
var color = "#e07c8a";
var NYC = "New York City";
var LA = "Los Angeles";
var url = "/my/app/url2";
var some_url = "/my/app/url";
var row_count = row['available_count'];

data = '<td><div class="' + another_class + 'item-count-div" style="background-color:' + color + '"' + ' data-url="' + url + '"' + ' data-toggle="popover" data-content="" + row_count + '</div></td>'; 

Now, for the data-content attribute, I want it's value to be:

data-content = "<a href="some_url">NYC</a> <a href="some_url">LA</a>"

some_url, NYC, LA are all variables. How can I achieve this result? I'm having a hard time figuring this out.

I have tried to do this:

data-content="<a href="'+some_url+'">'+NYC+'</a>"' 

This didn't work and gives me weird ahref tag.


Solution

  • If you are using newer version, you can refer to the previous answer, otherwise you can do something like:

    Update: Following code works perfectly. It was html causing issue.

    var another_class = 'datatables-more';
    var color = "#e07c8a";
    var NYC = "New York City";
    var LA = "Los Angeles";
    var url = "/my/app/url2";
    var some_url = "/my/app/url";
    var row_count = row['available_count'];
    
    var dataContent = '<a href=\''+some_url+'\'>'+NYC+'</a> <a href=\''+some_url+'\'>'+LA+'</a>';
    
    var data = '<td> <div class="' + another_class + ' item-count-div" style="background-color:'+ color + ';" data-url="' + url + '" data-toggle="popover" data-content="'+dataContent+'" >' + row_count + '</div></td>';