1

I have a string that includes markdown text and I'm trying to convert it to html syntax. When I test in any regex tester, my code is good, but the powershell replace operator, just won't do it. I think I'm missing something, but not sure what.

Does anyone have any ideas?

Example:

$message = "This is a test: [Latest Release Notes](https://learn.microsoft.com/en-us/azure/devops/release-notes/2023/sprint-218-update)"
$markdownLinkRegex = "/\[([^\[\]]+)\]\(([^\(\)]+)\)/g"
# have tried both of these options below
$htmlmessage = $message -replace ([regex]::Escape($markdownLinkRegex)), "<a href='$2'>$1</a>"
$htmlmessage = $message -replace $markdownLinkRegex, "<a href='$2'>$1</a>"

I have tried adding extra '\' into the regex string, but that made it worse.

I am expecting to see this result:

$htmlmessage = "This is a test: <a href='https://learn.microsoft.com/en-us/azure/devops/release-notes/2023/sprint-218-update'>Latest Release Notes</a>"
huntantr
  • 23
  • 3

2 Answers2

0

PowerShell doesn't use the same syntax as JavaScript so it doesn't need /g

Maybe removing the global do flag will work

$message = "This is a test: [Latest Release Notes](https://learn.microsoft.com/en-us/azure/devops/release-notes/2023/sprint-218-update)"
$markdownLinkRegex = "\[([^\[\]]+)\]\(([^\(\)]+)\)"
$htmlmessage = $message -replace $markdownLinkRegex, "<a href='$2'>$1</a>"
0

The Microsoft.PowerShell.Utility Module comes with the ConvertFrom-Markdown cmdlet on PowerShell 7.2+ and it uses the markdig library to parse markdown files and strings.

Converting your string to its HTML representation is as simple as:

$message = "This is a test: [Latest Release Notes](https://learn.microsoft.com/en-us/azure/devops/release-notes/2023/sprint-218-update)"
(ConvertFrom-Markdown -InputObject $message).Html
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37