我有一个 body 属性,其中包含涉及 @username1 @username2 的文本。我想将昵称@user1@user2等更改为路由器链接,可以使用正则表达式来做到这一点吗?
最终代码需要像这样(链接配置文件中没有@)
<router-link :to='/profile/username1'></router-link>
我在此分享解决方案codepen https://codepen.io/cincarnato/pen/wvMyzEx
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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)