如果使用 replaceRE 存在于 Hugo Shortcode 中,则去掉最后一个“-”

问题描述

我在 Hugo 中使用短代码标题包装在 .md 页面上的链接中,以便我可以在同一页面上使用锚链接

代码标题转换为小写,并将空格和其他字符转换为破折号。问题是,如果标题末尾有问号或其他字符,短代码会在标题上留下尾随的“-”。如果存在结尾破折号 -,我该如何去掉它?

代码 link-heading.html :

{{ $id := .Get 0 | lower | replaceRE "[^0-9a-z]" "-" | replaceRE "-+" "-" -}}
<a href="#{{ $id }}">
  <h2>{{ .Get 0 }}</h2>
</a>

.md 文件中的简码用法

{{< link-heading "This is a String with a Trailing?" >}}

输出

<a href="#this-is-a-heading-with-a-trailing-">
<h2>This is a heading with a Trailing?</h2>
</a>

使用 Markdown 作为锚链接

## This is a String with a Trailing?

输出

<h2 id="this-is-a-heading-with-a-trailing">This is a heading with a Trailing?</h5>

问题在于短代码输出末尾的 -。我怎样才能去掉最后一个 - 如果它在上面的短代码 replaceRE 中使用 link-heading.html 存在?

解决方法

我想我可能在这里遗漏了一些东西,但如果您只想获取字符串末尾的 - 或者它前面有 ?,您可以执行以下操作:

enter image description here