Alt attribute encoding with JavaScript

僤鯓⒐⒋嵵緔 提交于 2019-11-27 15:34:47

Here's an alternative if you can't save your file using a Unicode format:

function decodeHTML(str) {
    return str.replace(/&#(\d+);?/g, function() {
        return String.fromCharCode(arguments[1])
    });
}

However, this requires you to use the numeric representation. In this case →.

JavaScript has its own system for escaping special characters in strings:

document.getElementById('formula').alt = 'A \u2192 B';
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Decode HTML entities using JavaScript</title>
  </head>
  <body>
    <img id="formula" src="vote-arrow-up-on.png" alt="A &rarr; C">
    <script>
      function html_entity_decode(str) {
        var p = document.createElement("p");
        p.innerHTML = str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
        return p.innerHTML;
      }

      var theValue = html_entity_decode('A &rarr; B');
      document.getElementById('formula').title = theValue;
    </script>
  </body>
</html>

Credits to The JavaScript Source.

EDIT: I changed the original code to only use innerHTML on a <p> element, instead of innerHTML and value of a <textarea>.

In that particular case, you don't have encode special HTML characters in JavaScript.

The W3C validator should not complain about this (just tested it) and the document should validate. If not post your code and I'll update my answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!