使用正则将Markdown转HTML时,如何移除残留的粗体双星号?
Fixing Markdown Bold to HTML Conversion
Key Issue
Your existing regex uses lookaheads/lookbehinds which only check for the presence of ** but don't include them in the match to replace. That's why the delimiters stay in the output.
Corrected Code
Use a regex that explicitly matches the ** delimiters and captures the content between them:
const text = 'My **bold\n\n** text.\n'; const boldRegex = /\*\*(.*?)\*\*/gs; const html = text.replace(boldRegex, '<strong>$1</strong>'); console.log(html);
Breakdown of the Regex
\*\*: Matches both the opening and closing bold markers(.*?): Non-greedy capture group to get all content between the markers (works across newlines thanks to thesflag)gsflags:g: Ensures all occurrences are replaced, not just the firsts: Makes the.character match newline characters, so multi-line bold content is handled correctly
Result
The output will now be: My <strong>bold\n\n</strong> text. with no residual ** delimiters.
内容的提问来源于stack exchange,提问作者Anton Olshanetsky
相关产品推荐
相关产品推荐

