如何用JavaScript将转义特殊字符(如")转换为原字符?
解决JSON中双重转义HTML实体的转换问题
你遇到的是双重转义问题:原始字符先被转成HTML实体(比如"转成"),存入JSON时这些实体又被转义了一次(&变成&),最终拿到的就是"这类双重转义序列。以下是不同编程语言的解决方法:
Python 实现
利用标准库html的unescape方法做两次解码:
import html escaped_str = ""Hello'World"" # 第一次解码还原HTML实体,第二次解码得到原始字符 final_str = html.unescape(html.unescape(escaped_str)) print(final_str) # 输出:"Hello'World"
JavaScript 实现
浏览器环境
借助临时DOM元素解析HTML实体:
const escapedStr = ""Hello'World""; const tempDiv = document.createElement('div'); // 第一次解码 tempDiv.innerHTML = escapedStr; const firstDecode = tempDiv.textContent; // 第二次解码 tempDiv.innerHTML = firstDecode; const finalStr = tempDiv.textContent; console.log(finalStr); // 输出:"Hello'World"
Node.js 环境
使用he库(可通过npm install he安装):
const he = require('he'); const escapedStr = ""Hello'World""; const finalStr = he.decode(he.decode(escapedStr)); console.log(finalStr); // 输出:"Hello'World"
Java 实现
Apache Commons Text 方案
使用StringEscapeUtils工具类(需引入Apache Commons Text依赖):
import org.apache.commons.text.StringEscapeUtils; public class EntityDecode { public static void main(String[] args) { String escapedStr = ""Hello'World""; String finalStr = StringEscapeUtils.unescapeHtml4(StringEscapeUtils.unescapeHtml4(escapedStr)); System.out.println(finalStr); // 输出:"Hello'World" } }
原生Java方案(无第三方依赖)
借助HTMLEditorKit解析:
import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.parser.ParserDelegator; import java.io.StringReader; import java.io.IOException; public class NativeHtmlDecode { private static String unescapeHtml(String html) throws IOException { StringBuffer result = new StringBuffer(); new ParserDelegator().parse(new StringReader(html), new HTMLEditorKit.ParserCallback() { @Override public void handleText(char[] data, int pos) { result.append(data); } }, false); return result.toString(); } public static void main(String[] args) throws IOException { String escapedStr = ""Hello'World""; String finalStr = unescapeHtml(unescapeHtml(escapedStr)); System.out.println(finalStr); // 输出:"Hello'World" } }
内容的提问来源于stack exchange,提问作者user19860297
相关产品推荐
相关产品推荐

