I need to use vue to detect all links in the text like if i have text like this
text : 'hello mate check this link'
i want this text when it buffering in div it appear like this
'hello mate check this link'
CodePudding user response:
The easiest way:
HTML
<span v-html="formattedText"></span>
Script
data() {
return {
text: 'Some kind of text with url www.google.com'
}
},
computed: {
formattedText() {
return this.linkify(this.text)
}
},
methods: {
linkify(inputText) {
const pattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9 &@#\/%?=~_|!:,.;]*[-A-Z0-9 &@#\/%=~_|])/gim;
let text = inputText.replace(pattern1, '<a href="$1" target="_blank">$1</a>');
const pattern2 = /(^|[^\/])(www\.[\S] (\b|$))/gim;
text = text.replace(pattern2, '$1<a href="http://$2" target="_blank">$2</a>');
return text;
}
It should meet your expectations, you can also change $1 and $2 in >$1|2</a>
to link.
CodePudding user response:
Well there are tons of libraries you could use to easily achieve this. But I personally would recommend Anchorme.js due to it's very small size. You can even customize the way the link will get handled when there are #ids
& @mentions
in text.
Vue.config.productionTip = false;
Vue.config.devtools = false;
new Vue({
el: "#app",
data: function() {
return {
text: `Library works with (http://www.google.com) or without (www.google.com) protocols in link. It works well on paths [www.github.io/something/something] and queries <wordpress.com/post.php?p=112> and even when query starts immediately after the TLDS "wordpress.com?p=112".`,
convertedText: ""
}
},
computed: {
htmlText() {
const converted = anchorme({
input: this.text,
// use some options
options: {
attributes: {
target: "_blank",
class: "detected"
}
},
// and extensions
extensions: [
// an extension for hashtag search
{
test: /#(\w|_) /gi,
transform: string =>
`<a href="https://a.b?s=${string.substr(1)}">${string}</a>`
},
// an extension for mentions
{
test: /@(\w|_) /gi,
transform: string =>
`<a href="https://a.b/${string.substr(1)}">${string}</a>`
}
]
});
return converted;
}
}
});
.htmlText {
background-color: #eeeeee;
padding: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://raw.githack.com/alexcorvi/anchorme.js/gh-pages/dist/browser/anchorme.min.js"></script>
<div id="app">
<textarea v-model="text" placeholder="enter text here" rows="3" cols="100">
</textarea>
<br/><br/>
<div class="htmlText" v-html="htmlText"></div>
</div>