CL. L
CL. L

Reputation: 257

Escape Single Quote Twice in Javascript

I come across the situation that I need to use the escape quote twice. Specifically, I need to put an variable in javascript function with single quotes, but the variable itself also has single quotes. Details can be seen below, the problem line is the one with class "tile_name":

template = '' +
    '<div name="'+$("#add_tags :selected").text()+'" class="tile" id="newsCat_gp" >' +
        '<span onclick="this.parentNode.style.display = \'none\';" class="closebtn">&times;</span>' +
        '<div class="tile__name"><b><font size="2px">'+$("#add_tags :selected").text()+'</b></font>  <a id="newCat__'+$("#idx_newsCat").text()+'img" style="text-align: right; float: right;" href="javascript:toggle5(\'newCat__\'+$("#idx_newsCat").text()+\'\', \'img\', \'newCat__\'+$("#idx_newsCat").text()+\'img\');"><img src=  "{% static '/img/minus.png' %}"></a> </div>' +
        '<div class="tile__list" id="newCat__'+$("#idx_newsCat").text()+'" style="display: block;"></div>' +
    '</div>';

I want the results is

\'newCat__\'+$("#idx_newsCat").text()+\'\' 

becomes

'newCat__'+$("#idx_newsCat").text()+' ' 

like what in the tile_list class, and finally give the results of newCat__20,

where 20 is held by $("#idx_newsCat").text().

Could anyone has the idea? Many thanks.

Upvotes: 0

Views: 207

Answers (2)

Mahesh Odedra
Mahesh Odedra

Reputation: 59

maybe this will help

var template = '' +
    '<div name="'+$("#add_tags :selected").text()+'" class="tile" id="newsCat_gp" >' +
        '<span onclick="this.parentNode.style.display = \'none\';" class="closebtn">&times;</span>' +
        '<div class="tile__name"><b><font size="2px">'+$("#add_tags :selected").text()+'</b></font>  <a id="newCat__'+$("#idx_newsCat").text()+'img" style="text-align: right; float: right;" href="javascript:toggle5(\'newCat__\'+$("#idx_newsCat").text()+\'\', \'img\', \'newCat__\'+$("#idx_newsCat").text()+\'img\');"><img src=  "{% static \'/img/minus.png\' %}"></a> </div>' +
        '<div class="tile__list" id="newCat__'+$("#idx_newsCat").text()+'" style="display: block;"></div>' +
    '</div>';

$('body').append(template);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

Upvotes: 0

Marco Moretti
Marco Moretti

Reputation: 689

You have to not escape ' where you concat string

javascript:toggle5(\'newCat__'+$("#idx_newsCat").text()+'\', \'img\', \'newCat__'+$("#idx_newsCat").text()+'img\');

Upvotes: 1

Related Questions