简体   繁体   中英

Js escape special characters

I've always escaped non-ASCII characters (such as à , ñ , é ) as HTML entities ( à , &entilde; , é ), even if I'm using charset UTF-8 (just for text editor support and semplicity).

My problem is that I keep all the text in external PHP files for a multi-language purpose.

The problem comes when I have to escape strings which have to be alerted:

This <button onclick="alert('&agrave;&egrave;&igrave;&ograve;&ugrave;')">Click me</button> outputs this: àèìòù ,

while this <script>alert("&agrave;&egrave;&igrave;&ograve;&ugrave;")</script> outputs this: &agrave;&egrave;&igrave;&ograve;&ugrave; .


Which is the reason for it?

Since I want to escape characters in the second example too, how could I do that in a way supported by both examples?

Those escaped chars are only readable by HTML.

A quick and dirty way if you want to handle them in the JS code (with JQuery though) is by adding them to an element and reading the output, otherwise if you just want to display your output somewhere in the page, it's super easy:)

See both examples below:

 var myString = "&agrave;&egrave;&igrave;&ograve;&ugrave;"; var escaped = $('<textarea />').html(myString).text(); alert(escaped); document.getElementById("myElement").innerHTML = myString;
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span id="myElement">a</span>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM