Pavel Shepelenko
Pavel Shepelenko

Reputation: 440

Making links in the text of a div clickable

I'm trying to make URLs in a text clickable using Nuxt/Vue.

The input text is: Learning Outside the Box - https://learningoutsidethebox.com

I have a method that converts it to a link:

setLinks(text) {
  var Rexp = /(\b(https?|ftp|file):\/\/([-A-Z0-9+&@#%?=~_|!:,.;]*)([-A-Z0-9+&@#%?\/=~_|!:,.;]*)[-A-Z0-9+&@#\/%=~_|])/ig;
              
  return text.replace(Rexp, "<NuxtLink to='$1' target='_blank'>$1</NuxtLink>");
}

After that I get a result: Learning Outside the Box - <NuxtLink to='https://learningoutsidethebox.com' target='_blank'>https://learningoutsidethebox.com</NuxtLink>. But it is still not clickable.

Changing to <a> didn't solve the problem.

Could you please clarify, what should I do to make this text become a working link?

Upvotes: 2

Views: 2026

Answers (1)

Nikola Pavicevic
Nikola Pavicevic

Reputation: 23490

You can try with a tag and v-html:

new Vue({
  el: '#demo',
  data() {
    return {
      url: 'Learning Outside the Box - https://learningoutsidethebox.com'
    }
  },
  computed: {
    getLink() {
      return this.setLinks(this.url)
    }
  },
  methods: {
    setLinks(text) {
      const Rexp = /(\b(https?|ftp|file):\/\/([-A-Z0-9+&@#%?=~_|!:,.;]*)([-A-Z0-9+&@#%?\/=~_|!:,.;]*)[-A-Z0-9+&@#\/%=~_|])/ig;
      return text.replace(Rexp, "<a href='$1' target='_blank'>$1</a>");
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div v-html="getLink"></div>
</div>

Upvotes: 1

Related Questions