escaping double quotes in a javascript split

0

I have the following code that shows the results of the database in a modal window, but for example in the description field there are parts of the text saved with quotation marks, for example to indicate inches 3 ", and when printing the information in the modal window, it only appears to where the quotes are, the rest of the fields no longer print them, how can I escape those quotes to show the rest of the information from there?

  $(".btn-view-producto").on("click", function(){
        var producto = $(this).val(); 
        var infoproducto = producto.split("*");      
        html = "<p><strong>Codigo:</strong>"+infoproducto[1]+"</p>"
        html += "<p><strong>Nombre:</strong>"+infoproducto[2]+"</p>"
        html += "<p><strong>Descripcion:</strong>"+infoproducto[3]+"</p>"
        html += "<p><strong>Precio:</strong>"+infoproducto[4]+"</p>"
        $("#modal-default .modal-body").html(html);
    });
    
asked by Francisco 17.12.2017 в 16:44
source

2 answers

0

There are several possibilities to correct it, so choose the one you like the most or the one that works best for you, after all. I understand that the problem is given to you by the infoproducto array []. Then I show you the possible solutions by way of example:

1. Mix single and double quotes.

    // simples fuera, dobles dentro
    infoproducto[4] = '<li><p>Pulgadas: 30"</p></li>';
    // dobles fuera, simples dentro
    infoproducto[4] = "<li><p>Pulgadas: 30'</p></li>";

2. Using escape sequences.

    // SdE (\) para comillas dobles
    infoproducto[4] = "<li><p>Pulgadas: 30\"</p></li>";
    // SdE (\) para comillas simples
    infoproducto[4] = '<li><p>Pulgadas: 30\'</p></li>';

The last possibility I can think of would be to use &quot; , which would surely work in this particular case, too, due to the HTML context.

However, if you prefer that the JavaScript code be independent for any context, you can choose any of the above options, 1 or 2, without distinction.

I hope I have been of help. Greetings.

    
answered by 17.12.2017 в 18:19
0

My code works well in jsfiddle, input should not put double quotes in an attribute html, you should always put a

&quot;

but if you do not have another.

$(".btn-view-producto").on("click", function(){
    var producto = $(this).val(); 
    var infoproducto = producto.split("*"); 

    html = '
    <p><strong>Codigo:</strong> ${infoproducto[0]}</p>
    <p><strong>Nombre:</strong> ${infoproducto[1]}</p>
    <p><strong>Descripción:</strong> ${infoproducto[2]}</p>
    <p><strong>Precio:</strong> ${infoproducto[3]}</p>
    '
    $("#modal-default .modal-body").html(html);
});

You can use the notation of es6 which is much better, and as indicated by "'" you should not have problems with the quotes.

link

    
answered by 08.12.2018 в 01:05