Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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", '∑');
    });
});
like image 245
kuruvi Avatar asked Oct 28 '12 13:10

kuruvi


2 Answers

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

like image 117
NotGaeL Avatar answered Oct 11 '22 13:10

NotGaeL


I know this is old, has been answered and accepted, but I was having a ton of trouble with changing a computed value field in an input form from javascript/jquery that included special characters like above. Anything I tried would cause the input form field to be filled with the complete escaped string. Mihai got me around it with the \u trick. ergo:

with input field:

<input type="text" name="string" id="string" />

I couldn't do

$('#string').value('&Phi;')

as the result would be the literal string '&Phi ;'

But could do

$('#string').value('\u03a0')

which works.

It might be obvious to most, but I wasted a good bit of time on this, and it is a hard question to ask due to so many general query terms.

like image 29
jaytho Avatar answered Oct 11 '22 13:10

jaytho