1、Java中json字符串包含html标签
/**
* json含有HTML标签的文本
* @param str
* @return
*/
public static String switchStr(String str){
str = str.replace("<","<");
str = str.replace(">",">");
str = str.replace(" "," ");
str = str.replace("&","&");
str = str.replace("\n","<br>");
return str;
}
例如:json字符串中包含html标签
String json= "<a href=‘http://www.baidu.com‘>百度一下</a>";
System.out.println(Test.switchStr(url));
输出结果:&lt;a&nbsp;href=‘http://www.baidu.com‘&gt;百度一下&lt;/a&gt;
2、js中的字符串中的html标签相互转换
(1)把html标签转为json
function htmlencode(str) {
str = str.replace(/&/g, ‘&‘);
str = str.replace(/</g, ‘<‘);
str = str.replace(/>/g, ‘>‘);
str = str.replace(/ /g, ‘ ‘);
str = str.replace(/t/g, ‘ ‘);
str = str.replace(/x22/g, ‘"‘);
str = str.replace(/(?:t| |v|r)*n/g, ‘<br />‘);
str = str.replace(/x27/g, ‘'‘);
return str;
}
例如:把js中的标签解析为字符串
var url = "<a href=‘http://www.baidu.com‘>百度一下</a>";
alert(htmlencode(url));
结果:&l&<br />bsp;&<br />bsp;;a href=‘h&<br />bsp;&<br />bsp;&<br />bsp;&<br />bsp;p://www.baidu.com‘&g&<br />bsp;&<br />bsp;;百度一下&l&<br />bsp;&<br />bsp;;/a&g&<br />bsp;&<br />bsp;;
(2)把json转为html标签
function htmldecode(str) {
str = str.replace(/&/gi, ‘&‘);
str = str.replace(/ /gi, ‘ ‘);
str = str.replace(/"/gi, ‘"‘);
str = str.replace(/'/g, "‘");
str = str.replace(/</gi, ‘<‘);
str = str.replace(/>/gi, ‘>‘);
str = str.replace(/<br[^>]*>(?:(rn)|r|n)?/gi, ‘n‘);
return str;
}
例如:js中的json中字符串转换为html标签
var json = "&lt;a&nbsp;href=‘http://www.baidu.com‘&gt;百度一下&lt;/a&gt;";
alert(htmldecode(json));
结果:<a href=‘http://www.baidu.com‘>百度一下</a>