使用$ .each解析字符串中的unicode

时间:2018-05-18 15:16:02

标签: javascript jquery

我正在尝试过滤来自onmousemove事件(工具提示)的字符串。
过滤后的字符串需要显示为文本。

问题是字符串如下:
需要过滤此字符串。 \ r \ n此字符串中还有unicode \ u00EB。

我想要的是什么:
此字符串需要过滤。
此字符串中还有unicode:ë

HTML 看起来如下:

<img onmousemove="showInfo(event,'This string needs to be filtered. \r\n There is also unicode in this string: \u00EB.');" onmouseout="hideInfo();" />

这是我尝试

$(document).ready(function() {
    $('td > img').each(function() {
        var toolTip = $(this).attr('onmousemove'),
            comment = toolTip.match(/([\'])(\\?.)*?\1/),
            parentCell = $(this).parent();

        $("div.timelineRow").css("padding", "7px");
        $("<td><b>Info:</b><span> " + comment[0] + "</span></td>").insertAfter(parentCell);
        $(this).insertAfter(parentCell);
    });
});

1 个答案:

答案 0 :(得分:0)

尝试使用JSON.parse解码Unicode字符。 (注意用双引号括起来使它成为有效的JSON)。

然后用<br>标记替换新行,将它们转换为HTML换行元素(浏览器不会渲染\r\n)。

e.g。

var htmlComment = JSON.parse('"' + comment[0] + '"').replace("\r\n", "<br>");
$("<td><b>Info:</b><span> " + htmlComment + "</span></td>").insertAfter(parentCell);