Home > other >  Making links in the text of a div clickable
Making links in the text of a div clickable

Time:11-12

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?

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related