[英]How to implement markdown in html and js
I am working on a website where a user can input a message that is sent to another user.我正在一个网站上工作,用户可以在其中输入发送给另一个用户的消息。 I want to implement Markdown so the user can use markdown on the message to be able to bold the message and other markdown options.
我想实现 Markdown 以便用户可以在消息上使用 markdown 以便能够加粗消息和其他 markdown 选项。 I want to implement this but I want to make sure that xss cannot happen and.innerHTML seems like it will cause issues.
我想实现这一点,但我想确保 xss 不会发生,并且 .innerHTML 似乎会导致问题。 I am not using node.
我没有使用节点。 Someone suggested using https://ourcodeworld.com/articles/read/396/how-to-convert-markdown-to-html-in-javascript-using-remarkable but it appears to be written in node and if it can be used directly in the js of a browser I have been unable to get it to work even copy pasting the code on the examples has not worked.
有人建议使用https://ourcodeworld.com/articles/read/396/how-to-convert-markdown-to-html-in-javascript-using-remarkable但它似乎是用节点编写的,如果可以使用直接在浏览器的 js 中,我无法让它工作,即使复制粘贴示例上的代码也不起作用。
function OnKeyDownOne(event) { if (event.which===13) { let textarea = document.getElementById("textareaOne").value; document.getElementById("textareaOne").value = ""; console.log(textarea); document.getElementById("textOne").innerHTML = textarea; } } function OnKeyDownTwo(event) { if (event.which===13) { let textarea = document.getElementById("textareaTwo").value; document.getElementById("textareaTwo").value = ""; console.log(textarea); document.getElementById("textTwo").innerHTML = textarea.replace(" *", "<b> ").replace("* ", " </b>"); } }
<textarea id="textareaOne" onkeydown="OnKeyDownOne(event)"></textarea> <p id="textOne"></p> <textarea id="textareaTwo" onkeydown="OnKeyDownTwo(event)"></textarea> <p id="textTwo"></p>
Based on the comments, I assume you are fine with using a library.根据评论,我假设您可以使用库。 You can pull any markdown library that you find on CDNs for example https://www.jsdelivr.com/package/npm/markdown-it .
您可以提取在 CDN 上找到的任何 markdown 库,例如https://www.jsdelivr.com/package/npm/markdown-it 。
var md = window.markdownit(); const input = document.getElementById("input") const output = document.getElementById("output") const render = () => { output.innerHTML = md.render(input.value); } input.onkeyup = render render()
* { box-sizing: border-box; margin: 0; }.container { display: flex; } #input, #output { flex: 1 1 0%; min-height: 100vh; border: 1px solid black; border-collapse: collapse; padding: 0.5rem; } #output { background-color: #D0D0D0; } #output:not(p) { margin-bottom: 1rem; } #output hr { margin-top: 1rem; } #output p { margin-bottom: 0.5rem; }
<script src="https://cdn.jsdelivr.net/npm/markdown-it@10.0.0/dist/markdown-it.min.js"></script> <div class="container"> <textarea id="input"> # Title Paragraph with **bold**. And also *italic*. --- Type something... </textarea> <div id="output"></div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.