[Vuejs]-How to make vueJS hyperlink using method

0👍

It appears you are using the incorrect group numbers.

$1 <a-href = "http://www.myUrl/$3">$2$3)</a>

Your pattern only contains, 2 groups.

(\(LINK )

and

(\d+)

So, I imagine, $3, will create an error, or return a null value.

If you want to capture only the number, and not the text, "LINK", you can use the following.

/\(LINK (\d+)\)/g

"… The hyperlink should be http://www.myUrl22 …"

So, for the replacement string, you can use the following.
Although, I am not entirely sure of the specific result you were looking for.

<a-href = "http://www.myUrl$1">(LINK $1)</a>

If you did need the text before the number, you can use the following pattern.

/\((.+) (\d+)\)/g
<a-href = "http://www.myUrl$1">($1 $2)</a>

0👍

v-if is used to conditionally render an element and usually expects a true/false value. To put another way, when applied to an element a v-if means "if true, render this element. If false, don’t render". Using a method with a v-if that returns an object or string doesn’t really make sense. The v-if should actually just be the first if statement in linkSearch method

<div v-if="data.Text.includes('LINK')">

Now, if that statement is true, then the <b-link> will be rendered, otherwise the div with the v-else will be rendered.

Let’s move on to getting the actual link now. First, :href="linkSearch.href" is incorrect. When you have an input parameter, you always need to provide it. Since you have defined the method as linkSearch(Text) (Text being the parameter), the href should be assigned like this

:href="linkSearch(data.Text).href"

Similarly, for the title:

:title="'View URL ' + linkSearch(data.Text).title"

Doing this way will cause linkSearch to run twice, once for each property you call it for… It’s not absolutely horrible, but it is inefficient. Assigning the href and title to different data variables and using those in your template would be a better idea.

Anyways, on to finally figuring out the actual string replacement. You are getting the LINK number as the second capture group, so that’s honestly all you need to use in the replacement. To keep things as simple as possible I’d just do this:

linkSearch(Text) {
  let num = Text.replace(/(\(LINK )(\d+)\)/g, '$2')
  return { title: 'LINK ', href: 'http://www.myUrl/' + num }
}

0👍

Thank you for your assistance. I was able to incorporate both of your suggestions and got it down to a one liner.

<div v-html="linkSearch(data.Text)"></div>

This the method used.

linkSearch(Text) {
  return Text.replace(
  /(\(LINK)(\d+)\)/g,
  '<a  target="_blank" title="https://myurl.com/$2" href ="https://myurl.com/$2">$1 $2)</a>'
  );
},

Leave a comment