How can I make clickable link of url's in my content?
Imagine you have piece of code {{post.caption}}
and it returns one paragraph, something like this:
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Numquam sunt nostrum nihil, illum nam ipsam at, ratione, https://google.com officia aperiam excepturi odio adipisci cum quo minus quibusdam laborum debitis voluptatibus temporibus.
I want https://google.com
to be linked automatically.
any suggestion?
CodePudding user response:
Maybe you can use v-html
after format the paragraph first?
CodePudding user response:
My solution bases on 3 step:
Step 1: Detect the href link in the variable.
Step 2: Change string link to a href tag by regex function.
Step 3: Use v-html to show it in browser.
You can test it by my vue simple example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vuejs 3</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<p>{{ message }}</p>
<p v-html="formatHrefLink(post.caption)"></p>
</div>
<script>
const { createApp } = Vue
createApp({
data() {
return {
message: 'Hello Vue!'
}
},
setup() {
var post = {};
return {
post
};
},
created() {
this.post.caption = `Lorem ipsum dolor, sit amet consectetur adipisicing elit. Numquam sunt nostrum nihil, illum nam ipsam at, ratione, https://google.com officia aperiam excepturi odio adipisci cum quo minus quibusdam laborum debitis voluptatibus temporibus. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Numquam sunt nostrum nihil, illum nam ipsam at, ratione, https://google.com officia aperiam excepturi odio adipisci cum quo minus quibusdam laborum debitis voluptatibus temporibus.Lorem ipsum dolor, sit amet consectetur adipisicing elit. Numquam sunt nostrum nihil, illum nam ipsam at, ratione, http://127.0.0.1:8080?test1=1&test2=abc#paragraph1 officia aperiam excepturi odio adipisci cum quo minus quibusdam laborum debitis voluptatibus temporibus.`;
},
methods: {
formatHrefLink(string) {
const regex = /(https?:\/\/[\w\.\d:?&=#] )/gm;
const subst = `<a href="$1">$1</a>`;
const result = string.replace(regex, subst);
return result;
}
}
}).mount('#app')
</script>
</body>
</html>
One problem is one party, do you agree with me : D