Can't remove single quote from a string inside an array in javascript

818 views Asked by At

I'm trying to output key value pairs from an object that has been stringified. But as soon as a single quote is detected, the data stops the output.

This is what I am getting:

[{"name":"john

But would like to see:

[{"name":"john's world"}]

This is the javascript code:

$(function() {

    var allObjects = [

        {
            name: "john's world",
            msg: "hello world"
        }, {
            name: "billy",
            msg: "goodbye"
        }
    ]

    apiResults(allObjects);

    function apiResults(processedItems) {

        var output = '';

        output += "<form class='add-item-form' method='get'>";
        output += "<label for='item-input'>Enter a name to save your list and press ENTER</label><br><br>";
        output += "<input type='text' id='item-input' name='item-input' title='Item' required autocomplete='off' placeholder='my wine list' autofocus>";
        output += "<input type='hidden' id='search-results-array'  name='search-results-array' value='" + JSON.stringify(processedItems) + "'>";
        output += "<button id='submitBtn' type='submit'>Add item</button>";
        output += "</form><br>";

        output += "<div class='container'>";
        $('#results').html(output);
        console.log(processedItems);
    }

    $(document).on('submit', '.add-item-form', function(event) {
        event.preventDefault();

        if (event.type === 'keypress' && event.which === 13 || event.type === 'submit') {


            // searchArray is attached to the api result
            var searchArray = $('#search-results-array').val();
            console.log("searchArray", searchArray);

        }

    });
});

Here's a jsfiddle of the problem: https://jsfiddle.net/marcusk1/mpahzfw4/15/

Your help is appreciated.

0

There are 0 answers