繁体   English   中英

将正则表达式添加到 Vue.js 数据对象

[英]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 这意味着如果文本输入包含xyzthis.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">

更新了 jsFiddle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM