HTML.JS.JSON special characters

JS to convert HTML special characters

These days to do the project, found that in JSON format from the server to pass data to the client, by JS displayed in HTML pages, there are some special characters can not be directly displayed as the background to pass over the '<b> msg </ b> # 'by JS displayed in the HTML page, the display became a msg #, not <b> msg </ b> #, this is because <and> between the content as HTML tags, while the & start with # as the HTML entity, so the display is not normal.

Solution is very simple, it render the JS before the conversion to the HTML page, what you can:

<div ></div>
<div ></div>
<script >
var str = '<b>msg</b>&nbsp;&#35;';

//js The string displayed in the HTML page
String.prototype.displayHtml= function(){
        // Converts a string into an array
        var strArr = this.split('');
        //HTML Page to display special characters, spaces, nature is not , But multiple spaces browser default displays only one, so replace
        var htmlChar="&<>";
        for(var i = 0; i< str.length;i++){
                // Find whether they contain special HTML characters
                if(htmlChar.indexOf(str.charAt(i)) !=-1){
                        // If present, they are converted to the corresponding HTML Entity
                        switch (str.charAt(i)) {
                                case '<':
                                case '>':
                                case '&':
        return strArr.join('');


Not previously assigned to the div above in the conversion, so the display is not normal, the second div display properly, show the following results:

HTML.JS.JSON special characters

JSP to convert HTML special characters

These are passed through the JS over the background data will be displayed on the page before the conversion, and sometimes through the JSP generated HTML page content, special characters at this time more than the above, while the conversion at this time need to convert and then output to the server HTML page. Jsp page, such as when generating HTML as follows:

<input type='txt' value='<%=msg %>'>

If msg is I'am>, the first random page, and the second text box displays an incorrect value

. This is because property values can use HTML tags may also use double quotes single quotes, if the HTML using single quotes, and the value is also included in single quotation marks, they will have problems, double quotes also have this problem, because most of the number of case, the page properties to use double quotes or single quotes do not regulate it, so the server is passed to the single quotes and double quotes need to be converted. In addition, like <,> would not have said, is to be converted, so this case should be at least 5 <>"'& This requires special conversion.

  // HTML Character conversion table
        public final static Map<String, String> HTML_CHAR = new HashMap<String, String>();
        static {
                HTML_CHAR.put("&", "&#38;");
                HTML_CHAR.put("\"", "&#34;");
                HTML_CHAR.put("<", "&#60;");
                HTML_CHAR.put(">", "&#62;");
                HTML_CHAR.put("'", "&#39;");

        public static final StringBuilder toHTMLChar(String str) {
                if (str == null) {
                        return new StringBuilder();
                StringBuilder sb = new StringBuilder(str);

                char tempChar;
                String tempStr;
                for (int i = 0; i < sb.length(); i++) {
                        tempChar = sb.charAt(i);
                        if (HTML_CHAR.containsKey(Character.toString(tempChar))) {
                                tempStr = (String) HTML_CHAR.get(Character
                                sb.replace(i, i + 1, tempStr);
                                i += tempStr.length() - 1;
                return sb;

before the output to HTML using the above toHTMLChar (msg). ToString () convert what you can:

Java to JSON conversion of special characters

Generated from the server as JSON formatted string back, and finally passed to the client is eval () function is dynamically generated Javascript, if the JSON string is malformed, the eval will parse error, often also the most common error is "'\ r \ n of these three characters, such as {name: 'I'am'} error when parsing the same, because JavaScript strings in single quotation marks can also be enclosed in double quotes, double quotes, like it has this problem. In addition , the string can not cross to write, that you can not write something like this: {name: "I '

am "}

So these 3 need to be converted, the other line may depend on the platform, so the \ n also needs to be converted, such as we need to throw the exception stack background information to JSON format back to the browser is displayed, you need to enter line conversion. Code:


                Writer wr = response.getWriter();

                        // The single quote escaping, because JSON String the string type can be in single quotation marks in the
                        exceptionTrace = exceptionTrace.replaceAll("'", "\\'");
                        // The double quotation marks escaped, because JSON String the string type can be in single quotation marks in the
                        exceptionTrace = exceptionTrace.replaceAll("\"", "\\"");

                        // The back-of-line conversions, because JSON String string does not appear explicitly of back-of-line
                        exceptionTrace = exceptionTrace.replaceAll("\r\n", "\\u000d\\u000a");
                        // Will wrap the conversion, because JSON String string cannot be an explicit line break
                        exceptionTrace = exceptionTrace.replaceAll("\n", "\\u000a");

                wr.write("{success:false,exception:true,msg:'" +exceptionTrace + "'}");

分类:Web 时间:2010-12-13 人气:164
blog comments powered by Disqus


  • prototype.js Development Notes (transfer) 1.3.1 2008-10-19

    Original Address: https: / / 1.1. Prototype What is this? Perhaps you have not used it, prototype.js is a JavaScript package written by Sam Stephenson. Wonderful idea to prepare a good secti

  • prototype.js 1.4 version of the developer manual (change) 2008-10-15

    See a very good thing in the country has not been a lot of people use them is really unhappy, so I spent a lot effort into this manual is translated into Chinese, as the article is very long, so the translation of the heavy workload and some of Local

  • Prototype.js and spring of ajax based pagination 2010-05-26

    This is based on prototype.js for ajax page, use the spring framework, custom page label each page into the list, the list into session, only the session page list of stored pages, do not go query the database, the performance will be higher First, c

  • JS frame child window will be stored in the contents of the div in the parent page 2010-10-11

    / / Index.htm <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title> New Page 1 </ title> <script language="javascript"> function getFrameBody () { / / C

  • prototype.js common functions 2011-01-14

    prototype.js commonly used functions: Example to explain the function name Element.toggle alternately hide or show Element.toggle (''div1'','' div2'') Element.hide Hide Element.hide (''div1'','' div2'') Show (''div1'','' div

  • 基础的prototype.js常用函数及其用法 2014-12-11

    prototype.js 常用函数 : Element.toggle 交替隐藏或显示 Element.toggle(''div1'',''div2'') Element.hide 隐藏 Element.hide(''div1'',''div2'') 显示''div1'',''div2'') Element.remove 删除 Element.remove(''div1'',''div2'') Element.getHeight 取得高度 El

  • prototype.js开发笔记 2012-05-11

    prototype官方网站: Prototype1.6官方下载 Ajax中国下载地址(121.23KB) Learn about what's new in version 1.6. Prototype SVN If you want the full development package (including unit tests), you can useSubversion to checkout the source

  • PeriodicalExecuter object in prototype.js 2009-03-15

    prototype.js defined PeriodicalExecuter object, provide a certain interval of time to repeat the logic of a method call. <div></div> <script> var i = 0; var p = new PeriodicalExecuter(showTime,0.1); //Create the instance. Each 0 .1Second

  • Prototype.js sent using ajax get request parameters garbled Chinese solution 2009-11-01

    Version: prototype, struts1.2. Front (page introduction prototype.js): 1, prototype-ajax.jsp <%@ page language="java" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getSchem

iOS 开发

Android 开发

Python 开发



PHP 开发

Ruby 开发






Javascript 开发

.NET 开发



Copyright (C), All Rights Reserved. 版权所有 闽ICP备15018612号

processed in 0.042 (s). 13 q(s)