2

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?

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Pavel Shepelenko
  • 350
  • 3
  • 17
  • Generating it as text will indeed not make it Vue-capable. Why are you even using this regex at the first place? Can't you pass the value dynamically? What is `setLinks`? – kissu Nov 11 '21 at 20:34
  • 1) Why are you even using this regex at the first place? - used it as an example https://stackoverflow.com/questions/49899107/making-text-urls-clickable-in-a-div 2)Could you clarify, where should I pass it? It's a content of a post created by user? setLinks substitutes a URL with a link – Pavel Shepelenko Nov 12 '21 at 08:03
  • `` should be enough actually. If you need to have it massage'd a bit, you could use a `computed`. – kissu Nov 12 '21 at 08:33
  • Also, don't use `a` tag for internal links inside of your SPA or you'll need to regenerate it all from scratch. – kissu Nov 12 '21 at 10:19

1 Answers1

1

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>
Nikola Pavicevic
  • 21,952
  • 9
  • 25
  • 46