Search code examples
jqueryspecial-characters

jQuery escaping special characters


Following script works well without having special character. Unfortunately, I have full of special characters to replace. How can I replace the texts with special characters in jQuery?

you can see my script has α, β, ∑ and more special characters.

thank you guys for the help.

HTML code

 <script src="http://code.jquery.com/jquery.js"></script>

 <input type="submit" name="replace" id="replace" value="Replace" />

 <div class="my_div">Default1 content1</div>
 <div class="my_div">Default2 content2</div>

script

$('#replace').click(function() {
    $('.my_div').text(function( idx, oldHtml){
        return oldHtml
            .replace("Default1", 'α')
            .replace("Default2", 'β')
            .replace("content1", '∑');
    });
});

Solution

  • You should check your server's default encoding settings match the document encoding and/or specify the proper encoding on the document. Some examples here: http://www.w3.org/International/O-charset.en.php

    Also you may/must HTML encode (at least some of) those special characters in order to display them correctly. You may escape them automatically using jQuery:

    $('<div />').text(stringtoescape).html();

    or manually following this conversion table http://www.w3.org/TR/html4/sgml/entities.html#h-24.3