Last active
June 23, 2021 00:38
-
-
Save meyer1994/8028f9e3c9cbc570de11bccc27f29b19 to your computer and use it in GitHub Desktop.
Extract links from text in Vue and add them as anchors (safely)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div> | |
<template v-for="(item, i) of text"> | |
<a v-if="item.link" :key="i" :href="item.text"> | |
{{ item.text }} | |
</a> | |
<template v-else> | |
{{ item.text }} | |
</template> | |
</template> | |
</div> | |
</template> | |
<script> | |
export default { | |
data: () => ({ | |
message: 'bananana http://codepen.io and http://google.com nice one bro http://cartera.com.br' | |
}), | |
computed: { | |
text () { | |
const HTTP = /https?:\/\/[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]/gim | |
const splitted = this.message.split(HTTP) | |
const urls = Array.from(this.message.matchAll(HTTP)) | |
.map(i => i[0]) | |
let res = [] | |
for (let i = 0; i < splitted.length; i++) { | |
res.push({ text: splitted[i], link: false }) | |
res.push({ text: urls[i], link: true }) | |
} | |
res.pop() | |
return res | |
} | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment