我有一个通过使用 Ajax 加载网页预览而获得的字符串。标题是这样的:
You Can\xe2\x80\x99t Handle the Truth About Facebook Ads, New Harvard Study Shows
我需要用人类可读的文本替换这些转义码。我已经尝试过了String.fromCharCode(),但是在混合字符串的情况下不会返回任何内容,除非您仅发送字符代码。
有没有一个函数可以用来修复这个字符串?
这是一种方法:
\n\nconst str_orig = \'You Can\\\\xe2\\\\x80\\\\x99t Handle the Truth About Facebook Ads, New Harvard Study Shows\';\r\n\r\nconsole.log("Before: " + str_orig);\r\n\r\nconst str_new = str_orig.replace(\r\n /(?:\\\\x[\\da-fA-F]{2})+/g,\r\n m => decodeURIComponent(m.replace(/\\\\x/g, \'%\'))\r\n);\r\n\r\nconsole.log("After: " + str_new);Run Code Online (Sandbox Code Playgroud)\r\n这个想法是在字符串中替换\\xby (生成 URL 编码的字符串),然后 apply ,它为我们处理 UTF-8 解码,转换为单个字符:%decodeURIComponent%e2%80%99\xe2\x80\x99 (U+2019, RIGHT SINGLE QUOTATION MARK)。
| 归档时间: |
|
| 查看次数: |
964 次 |
| 最近记录: |