I have a body property that contains text that involves @username1 @username2. I want to change where are nicknames @user1 @user2 etc to router-links, its possible to do it with
Use named routes and params for route
<router-link :to="{ name: 'user', params: { username: yourUserNameProp }}"></router-link>
Named routes:
const router = new VueRouter({
routes: [
// dynamic segments start with a colon
{ name:'user', path: '/profile/:username', component: User }
]
})
I share the solution in this codepen
CODE:
<template>
<div>
<h3>Original</h3>
<div id="original" class="box">
{{body}}
</div>
<h3>Replaced</h3>
<div id="replaced"
class="box"
v-html="bodyReplaced"
></div>
</div>
</template>
<script>
export default {
data() {
return {
body: 'Hi @jrambo and @jwick I am @cincarnato',
};
},
computed: {
bodyReplaced(){
/* Using string.replace
1 parameter: regex to match
2 parameter: a function that return the new text (the funcion receive the string matched by regular expression)
*/
return this.body.replace(
/@\w+/g,
(user) => '<a href="#" >'+user+'</a>'
)
}
}
};
</script>
<style>
.box{
border: 1px solid grey;
padding: 10px;
margin: 10px;
}
</style>