Search code examples
javascriptapostropheappendto

apostrophe issue with appendTo


Below are the two codes that I tried:

$( "<li class='item' id='item' name='"+infoitem+"'>"+ title +"</li>" ).appendTo( "#sortable" );
$( "<li class='item' id='item' name='"+infoitem+"'/>").html(title).appendTo( "#sortable" );

title containing apostrophe throws an error and it breaks the code...

How do I filter the text with \' and then re-add it as an acceptable html with the apostrophe?

Any suggestions would be great.

EDIT:

I got an working example of why its not working http://jsfiddle.net/cowmoohard/bxxmhe03/4/

In the original post I forgot to mention that the appendTo is in a function and it takes a string of characters included space. Please see the example above. Just edit it with ' in the string and then it'll stop working.


Solution

  • Try to use ' for javascript and obligatory use " for HTML. It will looks like:

    $('<li class="item" id="item" name="' + infoitem + '">' + title + '</li>').appendTo('#sortable');
        $('<li class="item" id="item" name="' + infoitem + '"/>').html(title).appendTo('#sortable');
    

    Edit1:

     var addedTitle="I'am a supe long string".replace('\'', '&#39;');
    

    this is in your fiddler code.

    Edit2: If you need to replace multiple things:

        String.prototype.replaceAll = function (searchvalue, newvalue) {
        return this.split(searchvalue).join(newvalue);
    };