我需要操作一个 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),但代码注释表明您希望它匹配 最后一个斜线之前的所有内容,这将需要类似以下的模式 (demo 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
公告capture group #1 包含您想要的 URL 部分,您可以按如下方式提取它:
const url = 'https://google.com/foo/bar';
const regex = /^(.+)\/.*$/ig;
const matches = regex.exec(url);
console.log(matches[1]) /* 1 = group index */
计算属性
你可以使用 computed property将包含有效的 URL
基于 this.myimage
中的字符串.在以下示例中,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`;
}
}
}
注意计算属性返回 undefined
如果this.myimage
是一个无效的 URL。这意味着 this.imgUrl
将是 undefined
如果文本输入包含 xyz
, 但它将是 http://google.com/a/b
如果输入有 http://google.com/a/b/c
.考虑到这一点,我们替换了 v-show
变量 imgUrl
这样 <img>
仅在 imgUrl
时显示已定义且不为空(即,当 this.myimage
是有效的 URL 字符串时)。我们还替换了 v-bind:src
的值与 imgUrl
,因为它已经包含完整的预期 URL 和 /home.jpg
附:
<img v-show="imgUrl" v-bind:src="imgUrl">
关于javascript - 将正则表达式添加到 Vue.js 数据对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50996407/