我正在嘗試將 Markdown 樣式的內容決議為 HTML 內容。
例如[test](https://test.com)--><a href="https://test.com">test</a>
要將超鏈接轉換為錨標記,我有以下宣告:
.replace(/\[([^\[] )\](\(([^)]*))/gim, '<a href="$3">$1</a>');
目前,這個正則運算式接受[test](https://test.com)作為輸入,但它無法匹配整個字串——它只能識別[test](https://test.com. 所以它<a href="https://test.com">test</a>)用那個尾隨括號輸出。
有人可以幫我修復上面的陳述句,以便它采用降價鏈接并按預期呈現錨標記嗎?對于檔案,這是進行此轉換的完整功能:
const markdown = `[test](https://test.com)`
const html = markdown.replace(/^### (.*$)/gim, '<h3>$1</h3>') // h3 tag
.replace(/^## (.*$)/gim, '<h2>$1</h2>') // h2 tag
.replace(/^# (.*$)/gim, '<h1>$1</h1>') // h1 tag
.replace(/\*\*(.*)\*\*/gim, '<b>$1</b>') // bold text
.replace(/\*(.*)\*/gim, '<i>$1</i>') // italic text
.replace(/\r\n|\r|\n/gim, '<br>') // linebreaks
.replace(/\[([^\[] )\](\(([^)]*))/gim, '<a href="$3">$1</a>'); // anchor tags
console.log(html)
uj5u.com熱心網友回復:
你只是錯過了一個 \)
const markdown = `[test](https://test.com)`
const html = markdown.replace(/^### (.*$)/gim, '<h3>$1</h3>') // h3 tag
.replace(/^## (.*$)/gim, '<h2>$1</h2>') // h2 tag
.replace(/^# (.*$)/gim, '<h1>$1</h1>') // h1 tag
.replace(/\*\*(.*)\*\*/gim, '<b>$1</b>') // bold text
.replace(/\*(.*)\*/gim, '<i>$1</i>') // italic text
.replace(/\r\n|\r|\n/gim, '<br>') // linebreaks
.replace(/\[([^\[] )\](\(([^)]*))\)/gim, '<a href="$3">$1</a>'); // anchor tags
console.log(html)
uj5u.com熱心網友回復:
不應該比這更復雜:
https://regex101.com/r/wKvNuy/1
const rxCommonMarkLink = /(\[([^\]] )])\(([^)] )\)/g;
function commonMarkLinkToAnchorTag(md) {
const anchor = md
? md.replace( rxCommonMarkLink , '<a href="$3"> $2 </a>' )
: md
;
}
但實際上,您不應該只使用適當的決議器嗎?
- https://remark.js.org/
這會決議 CommonMark 并為您提供一個 AST,您可以遍歷該 AST 來完成您需要的作業:https ://astexplorer.net/#/gist/0a92bbf654aca4fdfb3f139254cf0bad/ffe102014c188434c027e4632306
備注建立在:
- https://www.npmjs.com/package/micromark
CommonMark 決議器本身 - https://github.com/syntax-tree/mdast-util-from-markdown
包裹 Micromark 并生成 AST
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/398904.html
標籤:javascript 正则表达式 代替 降价
