I recently encountered a situation where I had a string stored in the database that looks something like this:
Lorem #ipsum dolor sit amet, #consectetur adipiscing elit, sed do #eiusmod tempor incididunt ut labore et dolore magna aliqua.
Within the string, you can see that some words are marked with hashtags (#ipsum).
My goal is to display the string within a span
, with all the hashtags turned into clickable links.
To accomplish this, I started by using the following code snippet:
let caption = ref(props.caption); // the text mentioned above
const tagRegex = /(#+[a-zA-Z0-9(_)]{1,})/g;
caption.value = caption.value.replace(tagRegex, `<a href="/$1">$1</a>`);
return () => h("span", { "innerHTML": caption.value, class: "text-pre" });
As expected, this code successfully renders the text with clickable links for each hashtag.
The next step involved replacing the a
elements with router-link
(specifically for Vue Router) and changing the href
attribute to to
.
However, simply making these replacements did not yield the desired outcome. The router-link
elements were rendered in the DOM but were not functioning as intended.
I attempted solutions such as replacing innerHTML
with v-html
, as well as creating multiple nodes using children, but these approaches did not work either.
If you have any insights or suggestions on how I can achieve the desired result, it would be greatly appreciated. Thank you.