[英]Adding Regex to a Vue.js Data Object
我需要操作一个 URL,以便它删除最后一个/
之后的所有内容,然后将我自己的文件名附加到末尾。
在最后/
之后删除所有内容的正则表达式是[^\/]+$
。
我尝试了下面 URL 中的代码,但挂载的功能似乎不起作用。 不确定这是否是因为 Vue2,因为该帖子已有 18 个月的历史。
https://forum.vuejs.org/t/binding-a-regexp-object-to-an-html-attribute/815
var vm = new Vue({
el: '#vue-instance',
data: {
myimage: ''
}
});
/* Regex to add is [^\/]+$ */
这是JSFiddle中的代码。
如何合并正则表达式以将 url 转换为 HTML 中的输出?
您提到的正则表达式模式将匹配 URL 的最后一个路径段(即最后一个斜杠之后的文本)( demo 1 ),但代码注释表明您希望它匹配最后一个斜杠之前的所有内容,这将需要模式如下(演示 2 ):
^(.+)\/.*$
正则表达式模式分解的解释:
^ # assert position at start of line
( # Start group 1
.+ # match any character (except line terminators), one or more times
) # End group 1
\/ # match `/` literally
.* # match any character (except line terminators), zero or more times
$ # assert position at end of line
注意捕获组#1 包含您想要的 URL 部分,您可以按如下方式提取它:
const url = 'https://google.com/foo/bar'; const regex = /^(.+)\/.*$/ig; const matches = regex.exec(url); console.log(matches[1]) /* 1 = group index */
您可以使用包含基于this.myimage
中的字符串的有效URL
的计算属性。 在以下示例中, imgUrl
计算属性解析this.myimage
以确保它是有效的URL
,并使用正则表达式解析最后一个斜杠之前的文本,然后将其作为/home.jpg
的前缀:
computed: {
imgUrl() {
let url = this.myimage;
// validate URL in `this.myimage`
try {
url = new URL(url).toString();
} catch (e) {
url = '';
}
if (url) {
const regex = /^(.+)\/.*$/ig;
const matches = regex.exec(url);
return matches && `${matches[1]}/home.jpg`;
}
}
}
请注意,如果this.myimage
是无效 URL,则计算属性返回undefined
。 这意味着如果文本输入包含xyz
, this.imgUrl
将是undefined
的,但如果输入包含http://google.com/a/b/c
http://google.com/a/b
考虑到这一点,我们将v-show
变量替换为imgUrl
,以便<img>
仅在定义了 imgUrl 且不为空时this.myimage
imgUrl
有效的 URL 字符串时)。 我们还将v-bind:src
的值替换为imgUrl
,因为它已经包含了完整的预期 URL,并附加了/home.jpg
:
<img v-show="imgUrl" v-bind:src="imgUrl">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.