有人可以帮助我解决以下问题吗?
基本上,我有一个JSON,其中文本带有\n
作为换行符。然后,我需要将其解析为markdown并将其转换为HTML。唯一的问题是,我尝试过的所有解析器都会忽略多个\n
实例。为了纠正这一点,我想出了以下想法,但是如您所见,它实际上根本不是很适应,而且很笨拙。
var converter = new showdown.Converter(),
description = data.description.replace(/\n\n/g, "\n<br/>\n<br/>");
description = data.description.replace(/\n\n\n/g, "\n<br/>\n<br/>\n<br/>");
description = data.description.replace(/\n\n\n\n/g, "\n<br/>\n<br/>\n<br/>\n<br/>");
var html = converter.makeHtml(description);
有没有办法做到这一点,如果连续有多个\n
,它会向每个<br/>
附加一个\n
?
谢谢:D
编辑:JSON在下面:
{
"description": "**A glitchy apple respring animation for Anemone.**\n\n\nOriginally requested by u/Cyko__, u/Momoske (Osctardo) decided to make a \"Smoke Ball\" animation for all devices with the 7 different resolutions:\n\n- 1136x640 (iPhone 5s)\n- 1334x750 (iPhone 6/7/8)\n- 1472x828 (iPhone 6/7/8 upscaled)\n- 1920x1080 (iPhone 6+/7+/8+)\n- 2208x1242 (iPhone 6+/7+/8+ upscaled)\n- 2436x1125 (iPhone X)\n- 2688x1242 (iPhone X upscaled)\n\n\nIn the comments of the [UPCOMING] post on r/jailbreak, 2 other people (u/MatRanc and u/R3IZ4) requested for:\n\n- An *\"Apple Glitch\"* respring animation\n- A *\"Verbose\"* respring animation, which was both reworked and updated to look great on all these devices and resolutions\n\n\nThis is the *\"Apple Glitch\"* respring animation, with a black version included for those of you with an OLED device (made by myself)!"
}
编辑2:这是一个jsfiddle,因此您可以看到会发生什么。只需从其中删除.replace()
,您就可以看到没有<br/>
的HTML应该是什么:https://jsfiddle.net/jacobcxdev/t7hj5mx0/。
答案 0 :(得分:0)
当然,您只需要用\ n
替换每个\ n:
{'1': 2, '2': 1, '3': 3, '4': 1, '5': 4}
答案 1 :(得分:0)
我设法找到了解决方案!
var converter = new showdown.Converter(),
description = data.description.replace(/\n{2,}/g, m => m.replace(/\n/g, "<br/>"));
description = description.replace(/<br\/>([^<])/g, "<br\/>\n\n$1");
var html = converter.makeHtml(description);
首次更换的信用额为Slai!